CQRS & Mediator in .NET Core — “A piece of cake”

Photo by Cédric Dhaenens on Unsplash

CQRS Overview

Photo by Will Francis on Unsplash
Photo by Ross Findon on Unsplash

So, what CQRS can help?

Firstly, separating the commands and queries allows the input and output model to be more focused on the specific task they are performing. This also makes testing the models simpler because they are less generalized and are therefore not bloated with additional code.

Command Query Responsibility Segregation

Well, a lot of files/classes need to be created…

As with any pattern, there are pros and cons to consider. Some may feel that the complexity added by having to manage different models may outweigh the benefits of separating them. Also, as with all patterns, the concept can be taken too far and start to become a burden on productivity and readability of the code. Therefore the degree to which one uses the CQRS pattern should be governed by each use case. If it’s not providing value, then don’t use it!

Photo by Erik Brolin on Unsplash


Photo by Bruno Kelzer on Unsplash
  • Reducing the number of connections between classes.
  • Encapsulation of objects using the mediator interface.
  • Providing a unified interface to managing dependencies between classes.
Install-Package MediatR
dotnet add package MediatR

Unit Test

Let’s write some unit test script to test our OrderController

Explicit Dependencies Principle

Although the code sample above already helped us to resolve some issue with applying CQRS, however, it introduced a new problem with hiding Dependency Injection implementation (we are done this via MediatR).

  • Run-time errors on the execution of a method.
  • Harder to trace dependencies: Devs maintaining the code have to understand the naming conventions, how the call stack for request handlers looks like, etc. in order to resolve dependencies. It may increase maintenance costs.


Together, we finish a sample project that applies CQRS and Mediator pattern. They are two separated design patterns — please remember this.





Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Thanh Le

A Software Technical Architect — Who code for food and write for fun :)