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. 
  1. Request/Command: A simple class representing the action you want to perform (e.g., CreateUserCommand).
  2. Handler: A class implementing IRequestHandler<TRequest, TResponse> that contains the actual business logic.
  3. The Mediator: An IMediator instance (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

Popular posts from this blog

What is the importance of EDMX file in Entity Framework

TRIGGER in sql server

Sending Email in asp.net or mvc using gmail or other smpt.