- What is MediatR library
- What is Mediator Pattern?
- What is Command Query Responsibility Segregation (CQRS)
- How to implement MediatR in .NET Core application
This article will show you how to use the MediatR
package in the .net core application with some advanced features. By the end of this article, you will be learning the following
- What is CQRS?
- How to integrate
MediatR
in .net core application - How to configure
MediatR
pipeline in .net core application
What is MediatR library
The media library worked with two essential programming design designs: CQRS and Mediator design.
What is Mediator Pattern?
As per Wikipedia- The mediator pattern is a behavioral pattern that defines an object that encapsulates how a set of objects interact. Mediator pattern reduces the dependencies between communicating objects, thereby reducing coupling.
What is Command Query Responsibility Segregation (CQRS)
The goal of CQRS is to standardize the separation of a model’s command and query. It accomplishes this by recognizing that the requirements for reading and writing are very different and that supporting both in a single model may not be the best idea.
- The write model is used for processing commands (writes).
- To handle queries, we can generate multiple read models. Therefore, it makes sense to have various read models; for example, GetBlogPost is one read model, GetBlogPostById is another.
- Read and write model can be optimized according to their needs
MediatR
the library provides all the characteristics of the CQRS design, so let's start implementing this in our .net core application
$ads={1}
How to implement MediatR in .NET Core application
Implementing MediatR in the .net core application is very straightforward
Install Mediatr package from NuGet
Install the MediatR package from NuGet by running the following command in terminal
dotnet add package MediatR
Install MediatR Dependency Injection Package
dotnet add package Mediatr.Extensions.Microsoft.DependencyInjection
Register the mediator in the ConfigureService
method of Startup
class
services.AddMediatR(typeof(Startup));
Create Query
public class GetAllPosts : Audit, IRequest<List<Post>>
{
}
Create Handler
public class GetAllPostsHandler : IRequestHandler<GetAllPosts, List<Post>>
{
public Task<List<Post>> Handle(GetAllPosts request, CancellationToken cancellationToken)
{
var posts = new List<Post>(){
new Post{Id=1,Title= "Mediator"},
new Post{Id=2,Title="Pipeline"}
};
return Task.FromResult(posts);
}
}
Inject the IMediator
in the control
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IMediator _mediator;
public ValuesController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Post>>> Get()
{
var allPosts = new GetAllPosts();
var result = await _mediator.Send(allPosts);
return Ok(new { Data = result, UpdatedDate = allPosts.UpdatedDate});
}
}
MediatR Pipeline
Suppose you want to add some pre and post-processing logic in your request. In that case, you can use MediatR pipeline behavior that is similar to .net core middleware.
Consider in our example that if you want to add UpdatedDate
in every response, you can create a pipeline and then add.
public class AuditPipeline<Tin, Tout> : IPipelineBehavior<Tin, Tout>
{
private readonly HttpContext _httpContext;
public AuditPipeline(IHttpContextAccessor httpContextAccessor)
{
_httpContext = httpContextAccessor.HttpContext;
}
public Task<Tout> Handle(Tin request, CancellationToken cancellationToken, RequestHandlerDelegate<Tout> next)
{
Console.WriteLine(request);
if (request is Audit audit)
{
audit.UpdatedDate = DateTime.Now;
}
return next();
}
}
Register the pipeline
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(AuditPipeline<,>));
This is open generic registration.{alertInfo}