CQRS Pattern With C# and MediatR (Part 2)

Implement CQRS pattern with MediatR library in a real world application

Abdelmajid BACO


Implementing CQRS pattern with MediatR library
Image from Pexels, a pick guitar or Médiator in french

This article is the continuation of the first one already published about “CQRS pattern with C# (Part 1)”, therefore, we will not go to explain CQRS proposal again. In this second part we are going to speak about MediatR Library and how it can implement read and write operations defined by CQRS.

By the end of this article we should understand how to use the MediateR Library to achieve the following goals:

1- Implement Commands and Queries operations.

2- Implement Notifications.

3- Use Dependency Injection to create a new instance of MediatR.

4- Use MediatR with Console application and Web API application.

MediatR Library

According to MediatR GitHub repository:

MediatR is a low-ambition library trying to solve a simple problem — decoupling the in-process sending of messages from handling messages. Cross-platform, supporting .NET Framework 4.6.1 and netstandard2.0.

In simple word, MediatR Library allows to dispatch messages to the appropriate handlers. It manages two kinds of messages:

- Requests/Responses, are commands and queries operations. Each operation has its own handler and may or not return a value.

- Notifications, are events raised due to the system modifications. Each event can have several handlers.

The following schema gives an overview of the MediatR Library purpose.

CQRS Architecture in Domain-Driven Design (DDD) and MediatR libradry
MediatR Library purpose

Install MediatR Library

To install the package via Nuget type the command: Install-Package MediatR or use .NET Core command line like this: dotnet add package MediatR

Real World Application

To represent a request (queries and commands) with response, MediatR Library uses a marker interface named IRequest<out TResponse>. For example:



Abdelmajid BACO

Senior Full Stack .Net / Angular Developer, Cloud & Azure DevOps, Carrier Manager, Husband, and Father.