I’m trying to set up a template for myself using .NET 8, PostgreSQL as database and CQRS pattern (with MediatR library).
I’ve done all the configuration, but when I try a simple QueryHandler, this is the error I get:
System.InvalidOperationException: The exception handler configured on ExceptionHandlerOptions produced a 404 status response. This InvalidOperationException containing the original exception was thrown since this is often due to a misconfigured ExceptionHandlingPath. If the exception handler is expected to return 404 status responses then set AllowStatusCode404Response to true.
---> System.InvalidOperationException: Cannot resolve 'MediatR.IRequestHandler`2[Application.Features.Todo.Queries.GetAllTodos.GetAllTodosQuery,System.Collections.Generic.List`1[Application.Dtos.Todo.TodoDto]]' from root provider because it requires scoped service 'Infrastructure.Data.ApplicationDbContext'.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(ServiceCallSite callSite, IServiceScope scope, IServiceScope rootScope)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(ServiceIdentifier serviceIdentifier, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at MediatR.Wrappers.RequestHandlerWrapperImpl`2.<>c__DisplayClass1_0.<Handle>g__Handler|0()
at MediatR.Wrappers.RequestHandlerWrapperImpl`2.Handle(IRequest`1 request, IServiceProvider serviceProvider, CancellationToken cancellationToken)
at MediatR.Mediator.Send[TResponse](IRequest`1 request, CancellationToken cancellationToken)
at Presentation.Endpoints.Todo.TodoEndpoints.<AddRoutes>b__3_0() in /Users/manuelraso/Documents/repo/wanderlust-nest/backend/src/Presentation/Endpoints/Todo/TodoEndpoints.cs:line 23
at Microsoft.AspNetCore.Http.RequestDelegateFactory.<ExecuteTaskOfT>g__ExecuteAwaited|133_0[T](Task`1 task, HttpContext httpContext, JsonTypeInfo`1 jsonTypeInfo)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddlewareImpl.<Invoke>g__Awaited|10_0(ExceptionHandlerMiddlewareImpl middleware, HttpContext context, Task task)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddlewareImpl.HandleException(HttpContext context, ExceptionDispatchInfo edi)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddlewareImpl.<Invoke>g__Awaited|10_0(ExceptionHandlerMiddlewareImpl middleware, HttpContext context, Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)
This is how I configured the DbContext (I tried with ServiceLifetime.Transient too):
var connectionString = configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<ApplicationDbContext>(
options => options.UseNpgsql(connectionString),
ServiceLifetime.Scoped);
This is how I register MediatR:
services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblies(
[
Assembly.GetExecutingAssembly(), // Assembly Application
]);
});
This is the QueryHandler:
internal sealed class GetAllTodosQueryHandler: IRequestHandler<GetAllTodosQuery, List<TodoDto>>
{
private readonly ApplicationDbContext _context;
public GetAllTodosQueryHandler(ApplicationDbContext context)
{
_context = context;
}
async Task<List<TodoDto>> IRequestHandler<GetAllTodosQuery, List<TodoDto>>.Handle(GetAllTodosQuery request, CancellationToken cancellationToken)
{
var test = await _context.Todos.ToListAsync(cancellationToken);
return await Task.FromResult(test.Adapt<List<TodoDto>>());
}
}
This is how I send the query (I tried both injecting ISender and creating a scope of MediatR, but same error):
public class TodoEndpoints : CarterModule
{
private readonly ISender _sender;
private readonly IServiceScopeFactory _serviceScopeFactory;
public TodoEndpoints(ISender sender, IServiceScopeFactory serviceScopeFactory)
: base("/todo")
{
_sender = sender;
_serviceScopeFactory = serviceScopeFactory;
}
public override void AddRoutes(IEndpointRouteBuilder app)
{
app.MapGet("/", async () => await _sender.Send(new GetAllTodosQuery()));
app.MapGet("/test", async () =>
{
using var scope = _serviceScopeFactory.CreateScope();
var mediator = scope.ServiceProvider.GetRequiredService<IMediator>();
return await mediator.Send(new GetAllTodosQuery());
});
}
}