In this blog, we are going to discuss on MediatR library and its implementation. The MediatR library was built to facilitate the below two primary software architecture patterns.
- CQRS – Command Query Responsibility Segregation.
- Mediator Pattern.
In this article, we will be checking the implementation of CQRS Pattern using MediatR.
The source code can be downloaded from here
Command Query Responsibility Segregation
CQRS stands for Command Query Responsibility Segregation. Its main intention is to split the responsibilities of Commands(saves) and Queries(reads) into different models.
If we consider the commonly used CRUD pattern (Create, Read, Update and Delete), usually, we will have a single interface with all these four operations. But CQRS, would split these operations into two models – one for queries (Read) and another one for commands (Create, Update and Delete)
In nutshell,
- It will accept incoming request.
- Handle that request and give back a response.
Let us now deep dive into a simple Web API with MediatR.
For this demo, I have used the below tools
- VS 2022 Community Edition Preview Version 17.4.0
- .NET 6.0
- Swagger/Postman
- MediatR Library
To begin with, create a ASP.NET Core Web API
Create a sample MediatRDemo API project and add a class library as below

Will create a model Student now
public class StudentModel
{
public int Id { get; set; }
public string Name { get; set; }
public string School { get; set; }
}
Now, we will create a Data Repository interface
public interface IDataRepository
{
List<StudentModel> GetStudents();
StudentModel AddStudent(StudentModel student);
}
Let us go ahead and create the Data Repository Implementation class
namespace MediatorDemo.Library.Data
{
public class DataRepository : IDataRepository
{
private static List<StudentModel> _students = new()
{
new StudentModel { Id=3456, Name="Prasad Raveendran", School="Mount Fort"},
new StudentModel { Id=6543, Name="Prabha Raveendran", School="St. Pious"}
};
public StudentModel AddStudent(StudentModel student)
{
_students.Add(student);
return student;
}
public List<StudentModel> GetStudents()
{
return _students;
}
}
}
So far so good. Now is the time to implement MediatR library.
Let us go ahead and install the package MediatR.
Install MediatR




Sarathlal SaseendranPosted Nov 7, 2022, 7:55 AM
Very nice article about MediatR