I am getting the following error when I call (MediatR) ISender.Send(<Request Object>) in my .net core 8.0 web API project. The solution in VS is a Web API project and a C# Library where all of the Domain logic is.
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.
System.InvalidOperationException: No service for type 'MediatR.IRequestHandler`2[Library Function]' has been registered.
I put the following line in program.cs to solve the problem but it did NOT help:
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
I'm wondering if there is something special I have to do to have the messaging work within the library? The MediatR package is installed in the library. Seems to me from all documentation this should be working.
There are two ways you can solve this problem without registering every RequestHandler to Requests like this
builder.Services.AddScoped(typeof(IRequestHandler<GetAccidentByIdQuery, GetAccidentResponse>), typeof(GetAccidentByIdQueryHandler));at given comment example.You need to get your Application layer assembly to use
RegisterServicesFromAssemblyto do that eighter you can get it with reflection or put your registrar in Application Layer.Application layer means the layer your RequestHandlers belong.
First Answer
program.cs
Second Answer
adding extension to your Application layer.
Then you must add this extension to
program.cslike you can see down below:program.cs
I hope it helps :)