CQRS and MediatR in ASP.NET core web API

Maulik Patel
4 min readDec 3, 2022

--

Here we are going to cover CQRS pattern with Mediator.

Let’s understand first when when we can use this.

For micro service architecture this is best fit pattern. Which provide asynchronous communication without direct dependency on services.

CQRS stands for “Command Query Responsibility Segregation”. It distribute responsibility between commands (save) and queries (read) into different model.

Key point being is that to create CQRS system, we just need to split the reads from the writes.

Let’s develop Product adding and listing functionality using CQRS + Mediator pattern.

Mediator Pattern

We can see some service send request to mediator. Mediator then invokes multiple services to handle message. There is no direct dependency on between services.

You can think of MediatR as an “in-process” Mediator implementation that helps us build CQRS systems. All communication between the user interface and the data store happens via MediatR.

Setup .NET core API with MediatR

First install MediatR package. Both packages will be installed in Application layer library project.

PM> install-package MediatR

Next, a package that wires up MediatR with the ASP.NET DI container:

PM> install-package MediatR.Extensions.Microsoft.DependencyInjection

Modify program.cs file

builder.Services.AddMediatR(typeof(Program));

Now, let’s create Product controller which send massages to MediatR.

Add constructor that initialize IMediatR instance.

IMediator interface allow us to send message to MediatR, which dispatches to relevant handlers.

From MediatR version 9.0 , IMediator interface split into two interface IPublisher and ISender.

ISender interface contain send method to send message to handlers.

For notification IPublisher method contains Publish method.

Add product model class and repository classes for Infrastructure layer to create and get product information.

After adding product entity, we need to generate migration script and update database for product table.

  • Add-migration productentity
  • Update-database productentity

Run these two commands to generate migration script and update sqlserver database.

Now let’s add Product repository.

IProductRepository.cs

ProductRepository.cs

Register dependency in program.cs file.

builder.Services.AddScoped<IProductRepository, ProductRepository>();

Separate Commands and queries

Let’s create three different folder commands, Queries and Handlers

There are two types of request in MediatR. One that returns a value and other don’t return value. Usually read/queries return value and command/writes don’t return value.

MediaR commands

First we see write command to create product.Inside command folder add AddProductCommand.cs file.

Now add handler AddProductHandler.cs file.

Let’s modify product controller.

Now run application.

Product has been created in database and we got successful response.

GetProductQuery

Now let’s define product query to read products.

Add GetProductQuery class to queries folder and implement it.

Add Query Handler inside handler folder.

Now let’s add get product api endpoint.

Run application and check list of created products.

Here we done with create product and get product list with CQRS + Mediator pattern.

For code refer GitHub repository: https://github.com/m-patel90/InvoiceService

Next article will covert further MediatR notifications, MediatR behaviors, commands and query to update records, get productbyid etc.

Thanks for reading!

Kindly follow me for keep learning.

--

--

Maulik Patel

Full stack Software Engineer. C# | .NET core | MSSQL | Azure | Docker | Angular12+