Introduction
In modern .NET development, building scalable, maintainable, and clean applications is a top priority. One of the most popular ways to achieve this is by following Clean Architecture principles. But as your application grows, managing communication between different layers can become messy.
This is where MediatR in .NET comes into play.
MediatR helps you implement the Mediator Design Pattern, which allows different parts of your application to communicate without directly depending on each other. This results in cleaner code, better separation of concerns, and easier testing.
In this article, we will understand how to use MediatR in .NET for clean architecture implementation in simple words, step by step, with practical examples.
What is MediatR in .NET?
MediatR is a lightweight library that helps you implement the Mediator pattern in .NET applications.
Simple Explanation
Instead of one class directly calling another class, MediatR acts like a middleman (mediator).
You send a request
MediatR forwards it to the correct handler
The handler processes it and returns a response
This removes tight coupling between components.
Why MediatR is Important for Clean Architecture
In Clean Architecture:
Each layer should be independent
Business logic should not depend on infrastructure
MediatR helps achieve this by:
Decoupling controllers from business logic
Moving logic into handlers
Making code more modular and testable
What is Clean Architecture in .NET?
Clean Architecture is a design approach where your application is divided into layers, each with a clear responsibility.
Common Layers
Presentation Layer → Controllers (API/UI)
Application Layer → Business logic (MediatR handlers)
Domain Layer → Core entities and rules
Infrastructure Layer → Database, external services
Key Idea
Dependencies should always point inward, not outward.
This keeps your core logic safe and independent.
Installing MediatR in .NET Project
To use MediatR, you first need to install it.
Using NuGet Package Manager
dotnet add package MediatR
dotnet add package MediatR.Extensions.Microsoft.DependencyInjection
Register MediatR in Program.cs
builder.Services.AddMediatR(typeof(Program));
Explanation
This tells .NET to scan your project and register all MediatR handlers automatically.
Core Concepts of MediatR
To understand how MediatR works, you need to know three main components.
1. Request (Command or Query)
A request represents an action.
Command → Changes data
Query → Reads data
public record GetUserQuery(int Id) : IRequest<string>;
2. Handler
A handler processes the request.
public class GetUserHandler : IRequestHandler<GetUserQuery, string>
{
public Task<string> Handle(GetUserQuery request, CancellationToken cancellationToken)
{
return Task.FromResult($"User Id: {request.Id}");
}
}
Join the conversation! Your thoughts help the community grow.