Use MediatR in ASP.NET or ASP.NET Core

Ashish Patel
.NET Hub
Published in
3 min readAug 3, 2021

Getting started with MediatR and CQRS Pattern — How to use MediatR in .NET and .NET Core?

MediatR in .NET

TL;DR

MediatR facilitates CQRS and Mediator patterns in .NET. It is a low-ambition library trying to solve a simple problem — decoupling the in-process sending of messages from handling messages.

MediatR supports request/response, commands, queries, notifications and events, synchronous and async with intelligent dispatching via C# generic variance. It also supports a publisher/subscriber pattern.

Most popular .NET Libraries every developer should know.

Mediator Pattern

The mediator pattern is a behavioral design pattern that helps to reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object. Mediator is used to reduce communication complexity between multiple objects or classes. This pattern provides a mediator class which normally handles all the communications between different classes and supports easy maintenance of the code by loose coupling.

CQRS

CQRS stands for Command and Query Responsibility Segregation, a pattern that separates read and update operations for a data store. Implementing CQRS in your application can maximize its performance, scalability, and security. The flexibility created by migrating to CQRS allows a system to better evolve over time and prevents update commands from causing merge conflicts at the domain level.

MediatR has two kinds of messages:

  1. Request/response messages, dispatched to a single handler.
  2. Notification messages, dispatched to multiple handlers.

Request/Response

Requests

Requests describe your commands and queries behavior. Requests are very simple request-response style messages, where a single request is synchronously handled by a single handler. For example, returning something from a database.

There are two flavors of requests in MediatR — ones that return a value, and ones that do not. Often this corresponds to reads/queries (returning a value) and writes/commands (usually doesn’t return a value).

  • IRequest<T> - the request returns a value.
  • IRequest - the request does not return a value.

Handler:

When a request is created, you will need a handler to solve request. Each request type has its own handler interface, as well as some helper base classes/interfaces. They depends on two parameters. i) request. ii) response.

  • IRequestHandler<T, U> - implement this and return Task<U>
  • RequestHandler<T, U> - inherit this and return U

Notifications

A single request being handled by a single handler. What if we want to handle a single request by multiple handlers? That is where notifications come in. In these situations, usually multiple independent operations that need to occur after some event.

For example, when new Customer is registered, you want to send email to customer and send SMS to administrator.

For notifications, first create your notification message and next, create zero or more handlers for your notification.

Configure MediatR in ASP.NET Core application

1. NuGet: To use MediatR, you need to install below NuGet packages.

PM> Install-Package MediatR
PM> Install-Package MediatR.Extensions.Microsoft.DependencyInjection

2. Configuration: MediatR has no dependencies. You need to configure a single factory delegate, used to instantiate all handlers, pipeline behaviors, and pre/post-processors. Then let MediatR know in what assemblies are those profiles defined by calling the IServiceCollection extension method AddMediatR at startup. This extension method, allowing you to register all handlers and pre/post-processors in a given assembly.

Commands and Queries

The request (query and command) inherit from IRequest<T> interface, where T indicates the return value. If you don’t have a return value, then inherit from IRequest.

The send method sends the object to the CreateCustomerCommmandHandler. The handler inherits from IRequestHandler<TRequest, TResponse> and implements a Handle method. This Handle method processes the CreateCustomerCommand.

MediatR Commands
MediatR Queries
Models

3. Usage: You are done with MediatR configuration. Set the IMediator object with dependency injection in controllers and send the query.

MediatR Sample Controller

Sample source code on GitHub.

Summary

MediatR is simple mediator pattern implementation in .NET. It keeps things separated and helps to keep Single Responsible Principle. It helps to decouple command/query and event-handling code.

--

--

Ashish Patel
.NET Hub

Cloud Architect • 4x AWS Certified • 6x Azure Certified • 1x Kubernetes Certified • MCP • .NET • Terraform • DevOps • Blogger [https://bit.ly/iamashishpatel]