.Net Core Web API with CQRS / MediatR

argon.js
3 min readMar 25, 2022

--

Let’s see how to develop a web API with CQRS

What is CQRS?

CQRS stands for Command and Query Responsibility Segregation. In simple English, Separate the Database reads and writes.

When to use CQRS?

CQRS is not a unicorn solution to use everywhere. If your application has more reads than writes to DB or It’s a part of large scalable micro-service architecture CQRS is a better solution.

But, If you have a basic and few endpoints it’s always better to go with another pattern (Like the Repository pattern).

CQRS adds complexity to the code but is easy to maintain and modify rapid changes.

What is MediatR?

MediatR is the most common and popular package used widely with CQRS that developed based on the Mediator pattern.

Let’s Start Coding…

Create a blank .net core web api solution and install the below nuget.

  1. MediatR
  2. MediatR.Extensions.Microsoft.DependencyInjection
Install NuGet packages

And Now let’s add MediatR to Startup.cs as Dependency Injection

Startup.cs

Let’s Create Commands and Queries Folders. Then add GetItemsQuery.cs and AddItemCommand.cs classes.

Folder structure

Now, let’s implement the GetItemsQuery.

This class holds all the data that we need to execute and the business logic and the response.

Pro tip: Make Query and Command classes static, will improve the code clean and easy maintainability.

GetItemsQuery.cs

As you can see above code section, We have query record which is similler to a query class as below.

public class Query : IRequest<Response>
{
}

But using record is more simple and clean as a best practice. If we have any properties in the Query class we can have that in record also. refer below code section.

public record Query(int id, string name, string itemCode) : IRequest<Response>;

similler to below

public class Query : IRequest<Response>
{
public int id { get; set; }
public string name { get; set; }
public string itemCode { get; set;}
}

Hope you understand how simple and clean to use record in this case than using class.

Response record also the similar to the Query record but it’s for the returning values.

Now, let’s implement the AddItemCommand.

AddItemCommand.cs

Let’s wire things app with Controller. Create a controller called ItemController.cs

First, We inject the mediator to the controller constructor so we can call that on each endpoints like below.

ItemController.cs

So that’s it. Source code you can find on this github link and Thank you for reading. Let me know if there anything I can improve or I have missed.

--

--