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.

1

There are 1 best solutions below

0
Emopusta On

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 RegisterServicesFromAssembly to 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

var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var applicationAssembly = Directory.GetFiles(path, "Application.dll").Select(AssemblyLoadContext.Default.LoadFromAssemblyPath).FirstOrDefault();

 services.AddMediatR(configuration =>
        {
  configuration.RegisterServicesFromAssembly(applicationAssembly);
});

Second Answer

adding extension to your Application layer.

public static class ApplicationServiceRegistration
{
    public static IServiceCollection AddApplicationServices(this IServiceCollection services)
    {
       
        services.AddMediatR(configuration =>
        {
            configuration.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
        });
        return services;
    }

Then you must add this extension to program.cs like you can see down below:

program.cs

builder.Services.AddApplicationServices();

I hope it helps :)