Why you need to try MediatR library for your .NET project

MediatR library is an open source implementation of mediator pattern for .NET applications. It was created by Jimmy Bogard (AutoMapper creator). In this article I will try to explain base concepts of this library and how it can be used in your applications.


Thin controllers

I think many of you have faced such type of controllers implementation:

You may think — what’s wrong with this implementation? We are just validating, mapping and saving object. And as the result send response to client. On the one hand you will be right, but on the other we can make it better.

I believe that controllers are just routing mechanism. So it should only proccess our requests by delegating all validation, mapping and another stuff to some services. This is standard approach. But you can do it in another way.


CQS

This approach allows separate read and write operations. But for commands and queries we need some handlers. And this is exactly where we can apply MediatR library.

As I mentioned before, this library is simple implementation of mediator pattern. This pattern allows implement commands/queries and handlers loosely coupled.


Show me the code

You can find sample application by link https://github.com/dmytrohridin/AspNetCoreMediatRSample. Bellow I will explain key points how to use MediatR library.

Note: The code in repository do not use any layers, DTOs and etc. It’s just demonstrate basic usage of library.

Requests

When you start use MediatR library, first thing you need to define is request. Requests describe your commands and queries behaviour.

GetOrderQuery describe query that require Id and return Order entity. All requests should implement IRequest interface. This interface is a contract which will be used by handler to process request.

Handlers

When request is created, you will need a handler.

All handlers should implement IRequestHandler interface. This interface depends on two parameters. First - request, second - response. More details about requests and handlers you can find here.

So, we have our query and handler, but how to use them?

All you need is to define controller, inject mediator and send query. That’s all.


So what?

As you see we got decoupled requests and handlers that controlled by the mediator. Also we got thin controller and approach to use CQS principle. This is not silver bullet but it makes sense to use it.