Unable to resolve service for type 'MediatR.IMediator'

Publish date: 2024-05-04

I try to make .NET Core API with CQRS, but i cannot build it because of MediatR error:

System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Core.Infrastructure.Domain.Queries.IQueryBus Lifetime: Scoped ImplementationType: Core.Infrastructure.Bus.QueryBus': Unable to resolve service for type 'MediatR.IMediator' while attempting to activate 'Core.Infrastructure.Bus.QueryBus'.)'

I've already added 'AddScope' for my QueryBus etc. Here's my code (app for AWS):

public class Startup { public const string AppS3BucketKey = "AppS3Bucket"; public Startup(IConfiguration configuration) { Configuration = configuration; } public static IConfiguration Configuration { get; private set; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAWSService<Amazon.S3.IAmazonS3>(); services.AddScoped<IQueryBus, QueryBus>(); services.AddScoped<IWarehouseRepository, WarehouseRepository>(); services.AddScoped<IRequestHandler<GetAllWarehouseDepartmentsQuery, IEnumerable<WarehouseDepartmentDto>>, WarehouseQueryHandler>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } 

QueryBus:

using System.Threading.Tasks; using Core.Infrastructure.Domain.Queries; using MediatR; namespace Core.Infrastructure.Bus { public class QueryBus : IQueryBus { private readonly IMediator _mediator; public QueryBus(IMediator mediator) { _mediator = mediator; } public Task<TResponse> Send<TQuery, TResponse>(TQuery query) where TQuery : IQuery<TResponse> { return _mediator.Send(query); } } } 

IQueryBus:

using System.Threading.Tasks; namespace Core.Infrastructure.Domain.Queries { public interface IQueryBus { Task<TResponse> Send<TQuery, TResponse>(TQuery query) where TQuery : IQuery<TResponse>; } } 

Thanks for help

3 Answers

You have not registered Mediatr itself at startup, so the DI container is failing to resolve it, as the error suggests.

You can add the MediatR DI extensions from NuGet and then register MediatR at startup:

To use, with an IServiceCollection instance:

services.AddMediatR(typeof(MyHandler));

or with an assembly:

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

Note, to use the above extension methods, you may need to add:

using MediatR; 

https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection

https://www.nuget.org/packages/MediatR.Extensions.Microsoft.DependencyInjection/

3

If your project fails to use the following action:

services.AddMediatR(typeof(MyHandler)); 

Then in addition install the NuGet package: MediatR.Extensions.Microsoft.DependencyInjection

This way you can add the service to your configuration:

public void InstallServices(IServiceCollection services, IConfiguration configuration) { services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly())); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestValidationBehavior<,>)); } 
Assembly yourHandlerAssembly = typeof(TestQueryHandler).Assembly; builder.Services.AddTransient<TestQueryHandler, TestQueryHandler>(); builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(assemblyToScan)); 

The above is only when your Handler's assembly not on core API project.

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobWptZGiDcYGOrqWampyaerW7jKucrKecq7Juv8SrraKblWKzsL6MrbCpnV2isqW1wK2pZqGdmrGqrdOoqQ%3D%3D