CQRS Pattern With C# and MediatR (Part 2)
Implement CQRS pattern with MediatR library in a real world application
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.
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:
“Add a New Product” : this scenario is a command operation because it’ll make a change to the system.
I created a class called AddNewProductCommand
, this class is a simple DTO object that implement IRequest
.
Each command/query has its own handler, AddNewProductCommandHandler
defines a handler for AddNewProductCommand
.
To raise an event after a system modification we use the following code: await _mediator.Publish(new ProductCreated(product))
.
This instruction will be performed by the appropriate notification handler, in this case the class NewProductCreatedHandler
.
The ProductCreated
class must implement the marker interface to represent a notification. Like this:
Register MediatR
Now, if you have a webApi project you can register MediatR in Startup.cs using ConfigurationdServices
method. Make sure you have installed Microsoft.Extensions.DependencyInjection
before.
If you have a console project you can use the following method to register MediatR Library.
The following code shows the scenario “Add a new Product” API Controller.
You can get all the source code from GitHub:
Thanks for reading. I hope this article was helpful.