Search code examples
c#.net-corecqrsmediatr

MediatR Issue : Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler


I'm using .Net Core 3.1 and MediatR framework/library for query objects. While executing the webApi\endpoint, I am getting the below issue

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler2[Queries.GetOrderResultQuery,System.Collections.Generic.IEnumerable1[Models.Order.OrdersDto]] Lifetime: Transient ImplementationType: Queries.Handlers.GetOrderResultQueryHandler': Unable to resolve service for type 'Interfaces.Repositories.IOrderResultRepository' while attempting to activate 'Queries.Handlers.GetOrderResultQueryHandler'.)

This is my project Structure

ProjectStructure

  1. Microservice.API project is the WebAPI where I have the Controller with endpoints
  2. In AppCore project I have the handler GetOrderResultQueryHandler
  3. In StartUp.cs I have added services.AddMediatR

What I have tried I have tried the different options given in the net as below

//var mediatRTypes = new Type[] { typeof(AppCore.ServiceAppCore), typeof(Domain.OrderDomain) };
    //services.AddMediatR(mediatRTypes);
    services.AddMediatR(typeof(AppCore.ServiceAppCore),typeof(Domain.OrderDomain));//ServiceAppCore is a class in AppCore Project & OrderDomain is a class in Domain Project where I have Data Models
    //services.AddMediatR(typeof(Startup)); // <===Gives Error Handler was not found for request of type MediatR.IRequestHandler`
    //services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies());
    //services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
    //services.AddMediatR(Assembly.GetExecutingAssembly());// <===Gives Error Handler was not found for request of type MediatR.IRequestHandler`
    

For each of the options I get one or the other error mentioned below

  1. Handler was not found for request of type MediatR.IRequestHandler`
  2. Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler

I am new to this pattern and am not sure what I am missing here. Please suggest a resolution for this issue.


Solution

  • Check your Persistence project, you will see a RepositoryRegistration class in the Extensions folder. You should register your repository there like this:

    public static void AddRepositories(this IServiceCollection services)
    {    
        services.AddTransient<IYourRepositoryInterface, YourRepositoryClass>();        
    }