Search code examples
c#.netencapsulationmediatr

MediatR and Handlers


I have been rcently been advised to use MediatR in my API Controllers for encapsulation purposes.

I just want to know how does it know which handler to communicate with and when?

I checked the handlers in my IDE and they don't seem to be used or referenced anywhere


Solution

  • MediatR needs to be registered on the ServiceCollection using something like this:

    services.AddMediatR(cfg =>
         cfg.RegisterServicesFromAssembly(typeof(Startup).Assembly));
    

    If you take a look under the hood of what is actually happening in there (see source here) you will see that the MediatR finds every concrete implementation of interfaces of its own domain (IRequestHandler, IRequestHandler, INotificationHandler etc) and register it to the collection.

    Finally, when you call it, it knows what to invoke.