Search code examples
.netmediatr

mediatr - handler are not being found


My solution has the following structure:

awesome-project
   Awesome.Project.App
     Program.cs
   Awesome.Project.Domain
     Commands/
     Handlers/

I am using mediatr in a console application but it's throwing an exception when I try to call .Send():

Unhandled exception. System.AggregateException: One or more errors occurred. (No service for type 'MediatR.IRequestHandler`2[Awesome.Project.Domain.Commands.RequestBillCommand,System.String]' has been registered.)

And I have declared added mediatr to services:

using Awesome.Project.Domain.Commands;
using Microsoft.Extensions.DependencyInjection;
using MediatR;
using System.Reflection;

namespace Awesome.Project.App {
    public class Program
    {
        public static void Main(string[] args)
        {
            Run().Wait();            
        }

        private static async Task Run()
        {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var mediator = serviceProvider.GetRequiredService<IMediator>();
            var command = new RequestBillCommand();
            await mediator.Send(command);
        }

        public static void ConfigureServices(IServiceCollection services)
        {
            services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));            
        }

    }
}

My command class:

    public class RequestBillCommand : IRequest<string>
    {
     ...

     }

The handler:

public class RequestBillHandler : IRequestHandler< RequestBillCommand, string>
    { }

Any idea what is missing to register?


Solution

  • Your handlers are not being registered because they are not part of the same assembly Program is in. They live in the Awesome.Project.Domain assembly.

    Add all the required assemblies in the RegisterServicesFromAssembly call.