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

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.


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.


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