Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core MediatR error: Register your handlers with the container

I have a .Net Core app where i use the .AddMediatR extension to register the assembly for my commands and handlers following a CQRS approach.

In ConfigureServices in Startup.cs i have used the extension method from the official package MediatR.Extensions.Microsoft.DependencyInjection with the following parameter:

services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);  

The command and commandhandler classes are as follow:

AddEducationCommand.cs

public class AddEducationCommand : IRequest<bool>
{
    [DataMember]
    public int UniversityId { get; set; }

    [DataMember]
    public int FacultyId { get; set; }

    [DataMember]
    public string Name { get; set; }
}

AddEducationCommandHandler.cs

public class AddEducationCommandHandler : IRequestHandler<AddEducationCommand, bool>
    {
        private readonly IUniversityRepository _repository;
        public AddEducationCommandHandler(IUniversityRepository repository)
        {
            _repository = repository;
        }

        public async Task<bool> Handle(AddEducationCommand command, CancellationToken cancellationToken)
        {
            var university = await _repository.GetAsync(command.UniversityId);

            university.Faculties
                .FirstOrDefault(f => f.Id == command.FacultyId)
                .CreateEducation(command.Name);

            return await _repository.UnitOfWork.SaveEntitiesAsync();
        }
    }

When i run the REST endpoint that executes a simple await _mediator.Send(command); code, i get the following error from my log:

Error constructing handler for request of type MediatR.IRequestHandler`2[UniversityService.Application.Commands.AddEducationCommand,System.Boolean]. Register your handlers withthe container. See the samples in GitHub for examples.

I tried to look through the official examples from the docs without any luck. Does anyone know how i configure MediatR to work properly? Thanks in advance.

like image 390
Mike Hawkins Avatar asked Jun 09 '18 12:06

Mike Hawkins


Video Answer


4 Answers

I have met the same issue.

The problem is that this line code

services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly);

handles all the MediatR IRequest and IRequestHandlers.

but you created an IRepository interface and its implementation class which can't be handled by that MediatR.Extensions.Microsoft.DependencyInjection

so keep all your changes but add this - manually register this like

services.AddScoped(typeof(IUniversityRepository), typeof(UniversitySqlServerRepository));

then issue resolved.

like image 118
ske Avatar answered Oct 08 '22 06:10

ske


I went through the same problem and searched for hours but nothing found because this error is a very generic error. Apparently it looks like a MediatR problem but very often, it is NOT the case.

How I went to this conclusion?

To get the original exception, I opened Event Viewer application, which exists by default in windows

In the custom Views > Summary Page Events I found some errors, which corresponded to my application. In my case Errors was something like this:

An error occured during migration

Exception: 
System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString')
   at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
   at Microsoft.EntityFrameworkCore.MySqlDbContextOptionsExtensions.UseMySql(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 mySqlOptionsAction)

As the error says, connectionString was empty. Ultimately I found out that when I was publishing my application to get the dlls, appsettings.json was not in the published folder, due to which connectionString was not found, which is why migration failed. and ultimately, app crashed with a very generic error:

Error constructing handler for request of type MediatR.IRequestHandler. 

Register your handlers with the container. See the samples in GitHub for examples
like image 29
SU7 Avatar answered Oct 08 '22 06:10

SU7


For me, none of the other solutions worked unfortunately as I had already registered everything. The solution for me was adding the following line to my program.cs:

.UseDefaultServiceProvider(options => options.ValidateScopes = false);

So the CreateHostBuilder method will be changed to:

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    }).UseDefaultServiceProvider(options =>
    options.ValidateScopes = false); // needed for mediatr DI

Actually that is something to do with "scoped service", you may find this answer also related.

like image 7
Salah Akbari Avatar answered Oct 08 '22 05:10

Salah Akbari


I had the same problem and in my case when I was registering the dependencies that certain handler needed after I was calling services.AddMediatR() was the actual issue, after I started registering my dependencies before registering Mediator everything works fine.

I'm using dot net core 2.2 with the default DI container and MediatR 6.0.0.

like image 6
Frankely Diaz Avatar answered Oct 08 '22 04:10

Frankely Diaz