MediatR Series 1

Sun, Mar 21, 2021 2-minute read

MediatR’s basic

Usage

As the author states is

A low-ambition library trying to solve a simple problem — decoupling the in-process sending of messages from handling messages.

The library itself exceeded this in many aspects, allowing the developer to not only dispatch commands, but to create code, and add functionality in the cleanest way possible.

Show me the code!

    Install-Package MediatR
  • Second declare your command:
public class CreateUser : IRequest
{
    public CreateUser( User user ) => User = user;
    public User User { get; }
}
  • Implement the handler:
public class CreateUserHandler : IRequestHandler<CreateUser, Unit>
{
    public async Task<Unit> Handle(CreateUser request, CancellationToken cancellationToken)
    {
        //Implementation goes here
    }
}
  • And finally dispatch your command:
public class UsersController : BaseController
{
    private readonly IMediator _mediator;
    
    public UsersController(IMediator mediator) => _mediator = mediator;
    
    [HttpPost]
    public async Task<IActionResult> Post([FromBody]User user, CancellationToken cancellationToken)
    {
        await _mediator.Send(new CreateUser(user), cancellationToken);
		return Created();
    }
}

Seems simple, except for one thing

Unit

… what is that?

In order for the library to keep its internal code simple and consistent, every Request SHOULD return something.

Why SHOULD? Because it can be avoided if instead of implementing the interfaces

IRequest<>

and

IRequestHandler

we implement the interfaces

IRequest

and inherit from the class

AsyncRequestHandler

where we need to override the protected

protected virtual Task Handle(CreateUser request, CancellationToken cancellationToken)

method instead.

Which one to use? Is up to you. I prefer to return Unit and having simple testing in my code.

Wait? How is our code executed then?

  • Simplest way is to install any of the packages provided for your DI of choice (two examples, just chose one of them!)
// For Microsoft.DependencyInjection
Install-Package MediatR.Extensions.Microsoft.DependencyInjection
// For Autofac
Install-Package MediatR.Extensions.Autofac.DependencyInjection

and register the library and handlers like this:

services.AddMediatR(typeof(CreateUserHandler));

This will register every handler in the assembly of the type CreateUserHandler as transient, (please read the docs!)

Wtih this you have everything you need to start working with MediatR.

In the next series we will go into why I consider this library a MUST for almost every project.