Filter posts by Category Or Tag of the Blog section!

using MediatR in core

Tuesday, 17 January 2023

In ASP.NET Core, the MediatR library is a famous open-source library that provides a simple and clean way to implement the mediator pattern for decoupling requests and responses. The mediator pattern is a behavioral pattern that allows for the separation of objects that request or perform an action from objects that process the request. MediatR provides an implementation of the mediator pattern by using a message-based approach.


Here are the steps to use MediatR in an ASP.NET Core application:


  1. Install the MediatR NuGet package in your ASP.NET Core project.


Install-Package MediatR


  1. Define a request and response class. These classes represent the data that is being passed between the client and the server.


public class CreateUserRequest : IRequest<CreateUserResponse>


    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }


public class CreateUserResponse


    public int UserId { get; set; }



  1. Create a request handler to process the request.


public class CreateUserHandler : IRequestHandler<CreateUserRequest, CreateUserResponse>


    public async Task<CreateUserResponse> Handle(CreateUserRequest request, CancellationToken cancellationToken)


        // Add logic to create user

        var user = new User


            FirstName = request.FirstName,

            LastName = request.LastName,

            Email = request.Email


        // Save user to database


        await _dbContext.SaveChangesAsync(cancellationToken);

        return new CreateUserResponse { UserId = user.Id };




  1. Register the request handler and MediatR in the ASP.NET Core DI container.




  1. Inject the IMediator interface in your controller or service.


public class UserController : ControllerBase


    private readonly IMediator _mediator;

    public UserController(IMediator mediator)


        _mediator = mediator;



    public async Task<IActionResult> CreateUser(CreateUserRequest request)


        var response = await _mediator.Send(request);

        return Ok(response);




In this example, the IMediator interface is injected into the UserController. When the CreateUser action is called, the CreateUserRequest is passed to the IMediator, which then uses the registered CreateUserHandler to process the request and return the CreateUserResponse. This allows for a separation of concerns between the controller and the request processing logic, resulting in more maintainable and testable code. I’ve never used this library in my projects as I usually need more customization so I implement the pattern myself but it doesn’t mean that this library isn’t flexible.


comments powered by Disqus