MediatR usage in DDD with handler not found error

473 views Asked by At

i'm learning about CQRS and implementing MediatR in a DDD project. I've the following project structure:

Domain
    - Commands
        - Requests
        - Handlers
    - Models
    - Interfaces
        - Repositories

CrossCutting
    NativeInjectionBootstrapper.cs

Presentation
    - Controllers

So, in Presentation Project i've inject all repositories and other dependencies with the NativeInjectionBootstrapper.cs and i added services.AddMediatR(typeof(Startup)) in Startup.cs.

In Domain > Commands > Request i implement the IRequest<> interface.

In Domain > Commands > Handlers i implement the IRequestHandler<> interface.

The interfaces are injected successfully, but when request to controller i receive the following error:

System.InvalidOperationException: 
Handler was not found for request of type MediatR.IRequestHandler`2 [Domain.Commands.Requests.Product.NewProductRequest,System.String]. 
Register your handlers with the container. 
See the samples in GitHub for examples.

I've looking for help here and someone suggest another type of add MediatR in startup like services.AddMediatR(typeof(AddEducationCommand).GetTypeInfo().Assembly); but i've no success.

I was search about how to register the handlers but I couldn't find anything.

2

There are 2 answers

0
Augusto Henrique On

I tried to add the Domain Project Assembly in the services.AddMediatR() and it's work.

Like this:

services.AddMediatR(
     AppDomain.CurrentDomain.Load("Buzzy.Presentation"), 
     AppDomain.CurrentDomain.Load("Buzzy.Domain")
);

I don't know if this is a correct way, but works.

0
Plamen Pilev On

You need to register MediatR with the assemblies where your handlers are defined:

services.AddMediatR(typeof(AddEducationCommandHandler).Assembly);

Have you read the docs: https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection