What is MediatR? Why do we need it? And How to use it?
Mediator Pattern - The mediator pattern ensures that objects do not interact directly instead of through a mediator. It reduces coupling between objects which makes it easy to maintain the code. Mediator pattern unified the service interfaces around a common design, one request in, one response out.
MediatR is a simple, unambitious mediator implementation in .NET.
Let’s now dive deeper into the working of a simple web API with MediatR. Complete code for the same can be found here.
1. Create a new web API project.
![](/data/items/18860/01.png)
![](/data/items/18860/02.png)
OpenAPI support makes it easy to test the API.
2. Create a folder with these three classes.
![](/data/items/18860/03.png)
Solution Hierarchy
2.1 ApiRequestModel: This class represents a request for API.
![](/data/items/18860/04.png)
ApiRequestModel
— IRequest<> It represents a request with a response.
2.2 ApiResponseModel : This class represents a response of API.
![](/data/items/18860/05.png)
ApiResponseModel
2.3 ApiHandler: And this class keeps the logical part.
![](/data/items/18860/06.png)
ApiResponseModel
IRequesthandler<> binds request and response with handler class. The logic of API is kept in the Handle method.
3. Now let’s check the controller. I wrote a base controller that would be inherited by other controllers.
![](/data/items/18860/07.png)
ApiControllerBase
ISender is responsible for communication between different mediator-linked objects. It sends a request through a mediator pipeline to be handled by a single handler.
In this code, HomeController is inheriting the base controller. ApiController communicates with ApiHandler based on ApiRequestModel and ApiResponseModel pair.
![](/data/items/18860/08.png)
ApiController
You can test this API using swagger (OpenAPI).
![](/data/items/18860/09.png)
From the above example, you can see a separation of request, response, logic, and communication using MediatR. And if you want to move to CQRS (Command and Query Responsibility Segregation) pattern, the mediator makes the transition seamless.