Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to resolve service for type 'MediatR.IMediator'

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

like image 480
Michał Grzyśka Avatar asked May 01 '20 13:05

Michał Grzyśka


People also ask

How do I register MediatR in .NET core?

AddMvc(); services. AddMediatR(typeof(Startup)); This automatically 1) configures MediatR, and 2) registers all handlers found in the assembly.

What is MediatR unit?

What is MediatR? MediatR is an implementation of the mediator pattern. It is a behavioural software design pattern that helps you to build simpler code by making all components communicate via a "mediator" object, instead of directly with each other.

What is MediatR .NET core?

MediatR Requests are very simple request-response style messages, where a single request is synchronously handled by a single handler (synchronous from the request point of view, not C# internal async/await). Good use cases here would be returning something from a database or updating a database.


1 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);

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

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

like image 114
Adam Avatar answered Oct 06 '22 15:10

Adam