Unable to resolve service for type 'MediatR.IMediator'
Asked Answered
P

3

18

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

Pontonier answered 1/5, 2020 at 13:41 Comment(0)
T
33

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/

Tot answered 1/5, 2020 at 13:54 Comment(3)
Haven't found that info anywhere, saved my day, thank you!Pontonier
No problem! If this solved your issue, you can mark it as the answer for any future searchers.Tot
If you the error "System.TypeLoadException: Could not load type 'MediatR.ServiceFactory' from assembly 'MediatR" , then see : https://mcmap.net/q/478699/-could-not-load-type-39-mediatr-servicefactory-39Ardatharde
B
0

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<,>));
    }
Brackett answered 21/3, 2023 at 15:54 Comment(0)
T
0
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.

Tameshatamez answered 22/9, 2023 at 20:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.