Mediator Pattern in .NET with MediatR
The Mediator pattern in .NET Core is a behavioral design pattern that reduces coupling between components by forcing them to communicate indirectly through a central "mediator" object. Instead of classes having direct references to each other, they send messages to the mediator, which then routes them to the appropriate handlers.
Why Use It?
- Decoupling: Objects don't need to know about each other's existence or implementation details.
- Slim Controllers: In ASP.NET Core, it keeps API controllers thin by moving business logic into separate "handler" classes.
- Maintainability: Centralizing communication logic makes it easier to modify or extend individual components without ripple effects.
- CQRS Support: It is the standard way to implement Command Query Responsibility Segregation (CQRS), where "Commands" (writes) and "Queries" (reads) are handled separately
The Standard Implementation: MediatR
While you can build your own mediator, the MediatR NuGet package is the industry standard for .NET applications.
- Request/Command: A simple class representing the action you want to perform (e.g.,
CreateUserCommand). - Handler: A class implementing
IRequestHandler<TRequest, TResponse>that contains the actual business logic. - The Mediator: An
IMediatorinstance (injected via Dependency Injection) that sends the request to the correct handler.
In the .NET ecosystem, the most popular implementation of the Mediator pattern is MediatR.
Comments
Post a Comment