Member-only story
Implementing CQRS with MediatR in .NET
In my previous article, Understanding CQRS (Command Query Responsibility Segregation) Pattern in .NET, we implemented the CQRS pattern from scratch without relying on any external libraries. The goal was to understand how commands, queries, handlers, and dependency injection work together behind the scenes rather than hiding that complexity behind a framework.
If you haven’t read that article yet, I highly recommend starting there first. This article assumes you’re already familiar with the CQRS pattern and the project we built together.
Now that we understand the fundamentals, it’s time to improve our implementation by introducing MediatR.
One of the common observations in our previous implementation was that every controller had to inject the handlers it needed. As the application grows, the number of constructor dependencies also grows, making controllers more tightly coupled to individual handlers. While the application works perfectly fine, the code can become harder to maintain over time.
MediatR solves this by acting as a mediator between your controllers and handlers. Instead of controllers knowing about every command or query handler, they simply send a request through IMediator, and MediatR automatically finds and executes the appropriate handler. This keeps controllers cleaner and reduces direct dependencies without changing the overall CQRS design.
In this article, we’ll continue with the same Product Management Web API from the…









