CQRS and MediatR in .NET: A Practical Guide
As applications grow, maintaining business logic becomes increasingly challenging. What begins as a simple ASP.NET Core application with controllers, services, and repositories can gradually turn into a tightly coupled system where even small changes require modifications across multiple layers.
One architectural approach that helps address this challenge is Command Query Responsibility Segregation (CQRS). When combined with MediatR, it provides a structured way to organize application logic, improve separation of concerns, and make code easier to maintain and test.
In this article, we’ll explore how CQRS and MediatR work together in ASP.NET Core, examine practical implementation examples, and discuss when this approach makes sense.
Understanding CQRS
CQRS is an architectural pattern that separates operations that modify application state from operations that retrieve data.
It divides application responsibilities into two categories:
- Commands: Operations that change application state, such as creating an order, updating a customer, or cancelling a transaction.
- Queries: Operations that retrieve information without modifying application state.
In a traditional service-based architecture, both operations often exist in the same service:
public class OrderService
{
public Task<int> CreateOrderAsync(
CreateOrderRequest request);
public Task<OrderDto?> GetOrderAsync(int id);
}
Although this approach works well for smaller applications, large services can accumulate unrelated responsibilities as business requirements evolve.
CQRS allows each operation to have its own request model and handler, making the responsibilities explicit.
Importantly, CQRS does not require separate databases, microservices, or event sourcing. Read and write operations can share the same database while remaining logically separated.
What Is MediatR?
MediatR is a .NET library that implements the mediator pattern. It allows application components to communicate through requests and handlers without directly depending on one another.
Instead of a controller calling a service containing multiple business operations, it sends a request through MediatR.
MediatR then dispatches that request to its corresponding handler.
The typical request flow is:
API Controller → MediatR → Request Handler → Database
This approach provides several advantages:
Reduced coupling between controllers and application logic.
Clear separation of individual business operations.
Easier unit testing of handlers.
Centralized cross-cutting concerns through pipeline behaviors.
MediatR does not implement CQRS automatically. Rather, it provides useful building blocks for organizing commands and queries.
Implementing CQRS with MediatR
Let’s consider a simple Order Management application built using ASP.NET Core and Entity Framework Core.
We’ll implement two operations:
Create a new order using a command.
Retrieve an existing order using a query.
Step 1: Create a Command
A command represents an intention to modify application state.
using MediatR;
public record CreateOrderCommand(
int CustomerId,
decimal Amount) : IRequest<int>;
Here, IRequest<int> indicates that the command expects an integer response representing the newly created order ID.
Step 2: Implement the Command Handler
Each command has a dedicated handler responsible for executing the operation.
public class CreateOrderHandler
: IRequestHandler<CreateOrderCommand, int>
{
private readonly AppDbContext _context;
public CreateOrderHandler(AppDbContext context)
{
_context = context;
}
public async Task<int> Handle(
CreateOrderCommand request,
CancellationToken cancellationToken)
{
var order = new Order
{
CustomerId = request.CustomerId,
Amount = request.Amount
};
_context.Orders.Add(order);
await _context.SaveChangesAsync(
cancellationToken);
return order.Id;
}
}
The handler focuses exclusively on creating an order.
Validation, authorization, and other cross-cutting concerns can be handled separately, allowing the business operation to remain focused.
Step 3: Create a Query
Queries retrieve data without modifying application state.
public record GetOrderByIdQuery(int Id)
: IRequest<OrderDto?>;
The corresponding handler retrieves the requested order:
public class GetOrderByIdHandler
: IRequestHandler<GetOrderByIdQuery, OrderDto?>
{
private readonly AppDbContext _context;
public GetOrderByIdHandler(AppDbContext context)
{
_context = context;
}
public async Task<OrderDto?> Handle(
GetOrderByIdQuery request,
CancellationToken cancellationToken)
{
return await _context.Orders
.AsNoTracking()
.Where(o => o.Id == request.Id)
.Select(o => new OrderDto(
o.Id,
o.CustomerId,
o.Amount))
.FirstOrDefaultAsync(cancellationToken);
}
}
Using AsNoTracking() avoids unnecessary change tracking for read-only operations.
Projecting directly into a DTO also prevents loading entity properties that the response does not require.
Step 4: Connect MediatR to ASP.NET Core
Register MediatR in Program.cs:
builder.Services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssembly(
typeof(CreateOrderCommand).Assembly));
Now the controller can dispatch requests through ISender:
[ApiController]
[Route(“api/orders”)]
public class OrdersController : ControllerBase
{
private readonly ISender _sender;
public OrdersController(ISender sender)
{
_sender = sender;
}
[HttpPost]
public async Task<IActionResult> Create(
CreateOrderCommand command,
CancellationToken cancellationToken)
{
var id = await _sender.Send(
command, cancellationToken);
return CreatedAtAction(
nameof(GetById), new { id }, id);
}
[HttpGet(“{id:int}”)]
public async Task<IActionResult> GetById(
int id,
CancellationToken cancellationToken)
{
var order = await _sender.Send(
new GetOrderByIdQuery(id),
cancellationToken);
return order is null
? NotFound()
: Ok(order);
}
}
The controller no longer needs to know how orders are created or retrieved. Its responsibility is limited to handling HTTP requests and responses.
For this example, assume that Order, OrderDto, and AppDbContext are already defined.
Using Pipeline Behaviors for Cross-Cutting Concerns
One of MediatR’s most useful capabilities is its support for pipeline behaviors.
In enterprise applications, operations frequently require common functionality such as:
Request validation.
Structured logging.
Performance monitoring.
Transaction management.
Exception handling.
Instead of repeating this logic inside every handler, pipeline behaviors allow it to be implemented centrally.
For example, a logging behavior can record request execution:
public class LoggingBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly ILogger<LoggingBehavior
<TRequest, TResponse>> _logger;
public LoggingBehavior(
ILogger<LoggingBehavior<TRequest, TResponse>>
logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
_logger.LogInformation(
“Handling {RequestName}”,
typeof(TRequest).Name);
var response = await next(cancellationToken);
_logger.LogInformation(
“Completed {RequestName}”,
typeof(TRequest).Name);
return response;
}
}
Register the behavior through MediatR configuration:
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(
typeof(CreateOrderCommand).Assembly);
cfg.AddOpenBehavior(
typeof(LoggingBehavior<,>));
});
This ensures consistent logging across requests without duplicating code in individual handlers.
In production applications, sensitive request data should not be logged indiscriminately.
Real-World Best Practices
Implementing CQRS successfully requires more than creating separate command and query classes.
1. Keep handlers focused
Each handler should represent a clear business operation. Avoid creating handlers that perform multiple unrelated responsibilities.
2. Optimize reads independently
Queries often benefit from lightweight DTO projections, AsNoTracking(), pagination, and appropriate database indexes.
3. Validate before executing commands
Use validation pipelines to reject invalid requests before they reach business logic. Business invariants must still be enforced where appropriate.
4. Manage transactions carefully
Commands involving multiple database changes may require explicit transaction boundaries. Avoid assuming every command automatically needs its own transaction.
5. Test business behavior
Unit-test handlers independently, but also use integration tests to verify database interactions, transactions, and pipeline configuration.
When Should You Avoid CQRS?
CQRS is not always the right choice.
For small CRUD applications with straightforward business rules, introducing commands, queries, handlers, and pipeline behaviors can increase complexity without delivering meaningful benefits.
CQRS becomes more valuable when:
Business operations have distinct responsibilities.
Read and write requirements differ significantly.
Application complexity continues to grow.
Multiple developers work on independent features.
Cross-cutting concerns require consistent implementation.
The goal should be maintainability, not architectural complexity for its own sake.
Conclusion
CQRS and MediatR can provide a structured approach to building maintainable ASP.NET Core applications. By separating commands from queries and keeping handlers focused, teams can organize complex business logic more effectively.
However, successful architecture is about choosing the right level of abstraction. CQRS should solve real problems rather than become a mandatory pattern for every project.
Are you using CQRS and MediatR in your .NET applications? Share your experiences, challenges, and lessons learned in the comments. Exploring different implementation approaches can help teams make better architectural decisions.