What is MediatR?
-
MediatR is a lightweight mediator library for .NET.
-
It acts like a post office:
-
Your code sends a request (letter).
-
MediatR delivers it to the correct handler (person who processes that letter).
-
-
This removes the need for direct references between classes.
In short: No more “Controller calls Service calls Repository directly.”
Instead: Controller sends a message → MediatR finds the right handler.
2️⃣ Why Use MediatR?
-
✂ Loose Coupling: Request sender doesn’t know who handles it.
-
📦 Clean Architecture Fit: Keeps layers independent.
-
🧩 Supports Patterns: Perfect for CQRS (separate Command & Query handlers).
-
🧪 Easy Testing: Handlers are single-purpose classes.
3️⃣ Key Concepts
Term | Meaning |
---|---|
Request | The message you send (Command or Query). |
Handler | Class that processes the request. |
Notification | One-to-many broadcast message (like events). |
4️⃣ Basic Example
Install NuGet Package
Step A: Create a Request (Command or Query)
-
IRequest<TResponse>
= a request that expects a response.
Step B: Create a Handler
Step C: Register MediatR in Program.cs
Step D: Use It in a Controller or Service
-
Send()
delivers the request to the matching handler.
5️⃣ Notifications (Publish/Subscribe)
-
For broadcasting events to many handlers.
Notification class:
Handlers:
Publishing:
Both handlers run independently.
6️⃣ Common Uses in .NET
-
CQRS: Separate
Command
andQuery
handlers. -
Domain Events: Publish events like
UserRegistered
. -
Decoupling: Replace direct service calls.
7️⃣ Benefits Recap
-
✅ Cleaner, more maintainable code.
-
✅ Easy unit testing of each handler.
-
✅ Scales well as app grows.
Summary:
MediatR is a mediator pattern implementation for .NET.
It lets you send commands/queries and publish notifications without tight coupling.
Perfect for Clean Architecture + CQRS projects.