C
C#2y ago
demndev

✅ Cannot resolve scoped service...

What I did wrong? Here's how I injected IQueryHandlers to DI:
services.Scan(selector =>
{
selector.FromCallingAssembly()
.AddClasses(filter => { filter.AssignableTo(typeof(IQueryHandler<,>)); })
.AsImplementedInterfaces()
.WithScopedLifetime();
});
services.Scan(selector =>
{
selector.FromCallingAssembly()
.AddClasses(filter => { filter.AssignableTo(typeof(IQueryHandler<,>)); })
.AsImplementedInterfaces()
.WithScopedLifetime();
});
Injection of dispatchers:
services.AddSingleton<ICommandDispatcher, CommandDispatcher>()
.Decorate<ICommandDispatcher, CommandDispatcherDecorator>();
services.AddSingleton<IQueryDispatcher, QueryDispatcher>();
services.AddSingleton<ICommandDispatcher, CommandDispatcher>()
.Decorate<ICommandDispatcher, CommandDispatcherDecorator>();
services.AddSingleton<IQueryDispatcher, QueryDispatcher>();
QueryDispatcher:
public class QueryDispatcher : IQueryDispatcher
{
private readonly IServiceProvider _serviceProvider;

public QueryDispatcher(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider;

public Task<TQueryResult> Dispatch<TQuery, TQueryResult>(TQuery query, CancellationToken ct)
{
var handler = _serviceProvider.GetRequiredService<IQueryHandler<TQuery, TQueryResult>>();
return handler.Handle(query, ct);
}
}
public class QueryDispatcher : IQueryDispatcher
{
private readonly IServiceProvider _serviceProvider;

public QueryDispatcher(IServiceProvider serviceProvider) => _serviceProvider = serviceProvider;

public Task<TQueryResult> Dispatch<TQuery, TQueryResult>(TQuery query, CancellationToken ct)
{
var handler = _serviceProvider.GetRequiredService<IQueryHandler<TQuery, TQueryResult>>();
return handler.Handle(query, ct);
}
}
3 Replies
demndev
demndevOP2y ago
Cezary Piątek Blog
Why I don't use MediatR for CQRS
Is MediatR really suitable for implementing CQRS pattern?
Cracker
Cracker2y ago
are you trying to resolve scoped service inside singleton service ? both looks like singleton
demndev
demndevOP2y ago
oh, really. thank you!
Want results from more Discord servers?
Add your server