CQRS Pattern Using MediatR In .NET 5

In this article let us learn the basics of the CQRS pattern using the MediatR NuGet package in .Net 5.

We know how a traditional web API works. It mainly consists of the CRUD operations. All four operations are tied together inside an API controller.

  • C — Create

  • R — Read

  • U — Update

  • D — Delete.

To decouple the application we make interfaces for our information access layer, inject it in the constructor of the API controller and perform the actions. This turns out great and all looks great. Yet, as your application grows in size the number of dependencies also increases. Now we need to inject multiple interfaces in the API controller and hence the application complexity increases.

In order to solve this problem, let’s use CQRS & Mediator Patterns.

CQRS stands for Command Query Responsibility Segregation. That is separating Command (write) and Query (read) models of an application to scale read and write operations of an application independently. Instead of having all of the four CRUD operations together, let us segment them out into two different pieces.

The mediator is used to reducing communication complexity between multiple objects or classes. This pattern provides a mediator class that normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling. Mediator pattern falls under behavioral pattern category.

Basically, a Mediator performs 2 operations.

  • Accept the incoming request

  • Handles the incoming request and provides the response.

CQRS + Mediator Patterns are preferred over large projects.

Let’s get into the code and see how these CQRS & Mediator patterns work together.

Read data using CQRS & MediatR

Open Visual Studio 2019. Create an ASP.Net Core Web API project named EmployeeManagement.API. I have given the solution name as EmployeeManagementDemo. (You can give any name of your choice).