MediatR
MediatR is a package message dispatcher within the application. It's useful for implementing requests/responses such as commands, queries, and handlers. Also, MediatR allows sending messages and especially supports various architectural patterns in modern .NET and .NET Core applications. It’s introduced as a .NET Standard library, starting from .NET Core 2.0, 3.1, and till supports the latest .NET 9.0. Also, it's an open-source, powerful library to implement the Mediator pattern in .NET applications. Architecture that supports mediatR is mentioned below.
- Clean Architecture: Well-suited for decoupling the application layers from presentation and infrastructure layers. Clean Architecture is used to keep business logic isolated.
- CQRS (Command Query Responsibility Segregation): CQRS is fit for handling separate write and read operations (commands and queries) in request/responses APIs.
- DDD (Domain-Driven Design): This is suitable for loosely coupling applications that can be created with domain events and services.
- Event-Driven Architecture: it supports publishing and handling events using INotification and INotificationHandler<T>
- Test-Driven Development (TDD): This architecture Handlers are easy to unit test, it's isolated from controllers and infrastructure.
![MediatR Library]()
MediatR Features in .NET 9 Core
- .NET 9.0 minimal API and modular project structure enhancements in a better way
- Dynamic Database support provided for using the Entity Framework (SQL Server, PostgreSQL, MySQL, SQLite)
- Better developer experience in lightweight, testable service layers.
- MediatR is used for implementing CQRS and a separate layer like Application, Domain, and infrastructure.
- Event handling is improved with built-in support for Server-Sent Events (SSE),
Advantages of MediatR in the latest version of .NET
- Testability improved; unit test handlers are easy and isolated
- Good for large applications that maintain many modules and features
- Logging, Validation, and Caching are supported in Pipeline behaviours
- Efficient for real-time applications and event-driven applications, and streaming API like OpenAI’s