Search code examples
c#asp.net.net-6.0clean-architecturemediatr

Use MediatR with Class Library


i'm trying to use MediatR in my ASP.NET 6 application, but i need to write builder.Services.AddMediatR(typeof(ExampleCommandHandler).Assembly); for every handler. I was looking for a way to add just in single line like builder.Services.AddMediatR(typeof(Startup).Assembly);. But all the examples i saw throw the exception with message Register your handlers with the container.

I think this problem is because my Commands and my Command Handlers are in different class library, example of my folder structure:

.
└── MyApp/
    └── src/
        ├── MyApp.API/
        │   ├── Startup.cs
        │   └── ...
        ├── MyApp.ClassLibrary1/
        │   ├── Handlers/
        │   │   └── ExampleCommandHandler.cs
        │   └── ...
        └── MyApp.ClassLibrary2/
            ├── Commands/
            │   └── ExampleCommand.cs
            └── ...

Can someone help me?


Solution

  • To solve this problem i've used the following code, just replace ClassLibrary.Name with the name of your library:

    options.RegisterServicesFromAssembly(AppDomain.CurrentDomain.Load("ClassLibrary.Name"));