What is MediatR and Why Is It Used in ASP.NET Core?
Question
Answers
MediatR is a .NET library that implements the mediator pattern, allowing different parts of an application to communicate through mediator requests rather than directly depending on each other.
The basic idea is simple:
Instead of a controller directly calling several application services, the controller can send a request through a mediator:
Controller → MediatR → Request Handler → Domain/Application Logic
For example, instead of putting substantial business logic inside an ASP.NET Core controller, you might define:
CreateCustomerCommand
and a corresponding:
CreateCustomerCommandHandler
The controller sends the command through MediatR, and the handler processes it.
This can help create a cleaner separation between API endpoints, application use cases, and business logic.
MediatR is commonly associated with CQRS-style architectures, where commands represent operations that change state and queries represent operations that retrieve data.
For example:
Commands
- CreateOrder
- UpdateCustomer
- ApproveInvoice
Queries
- GetCustomer
- GetOrderDetails
- SearchProducts
Another powerful feature is the ability to use pipeline behaviors for cross-cutting concerns such as:
- Validation
- Logging
- Performance monitoring
- Transactions
- Authorization
- Exception handling
But there is an important architectural lesson here:
MediatR is not automatically required just because you're building an ASP.NET Core application.
For a small CRUD application, introducing MediatR everywhere can create unnecessary abstractions and additional classes.
For larger applications with clearly defined application use cases, complex business logic, CQRS, or cross-cutting requirements, the mediator pattern can provide meaningful architectural benefits.
Career takeaway
For students, learn the pattern before learning the library:
Dependency Coupling → Mediator Pattern → Commands/Queries → Handlers → Pipeline Behaviors → CQRS
For working .NET developers, the important interview question isn't:
“Have you used MediatR?”
It is:
“Why did you introduce MediatR, and what architectural problem did it solve?”
That answer demonstrates engineering maturity.