3

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?

João Pedro
  • 115
  • 1
  • 12
  • 1
    Some of the answers here might help: https://stackoverflow.com/questions/50774060/asp-net-core-mediatr-error-register-your-handlers-with-the-container – rene Oct 10 '22 at 17:23
  • 1
    When you call `.AddMediatR` you can pass multiple assemblies instead of just one, like `builder.Services.AddMediatR(typeof(ExampleCommandHandler).Assembly, typeof(ExampleCommand).Assembly);` – Scott Hannen Oct 10 '22 at 20:34
  • @ScottHannen If i use `builder.Services.AddMediatR(typeof(ExampleCommandHandler).Assembly);` works for every handler, but i don't know why. – João Pedro Oct 11 '22 at 16:27

2 Answers2

1

try builder.Services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies());

Chee Weng
  • 141
  • 5
0

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"));
João Pedro
  • 115
  • 1
  • 12