avatarAshish Patel

Summary

This context provides a detailed guide on using MediatR in ASP.NET or ASP.NET Core, including its installation, configuration, and usage.

Abstract

MediatR is a simple mediator pattern implementation in .NET that helps to decouple command/query and event-handling code. It facilitates CQRS and Mediator patterns, supporting request/response, commands, queries, notifications, and events, both synchronously and asynchronously. The guide explains the Mediator Pattern and CQRS, then delves into the specifics of request/response and notifications in MediatR. It also provides step-by-step instructions on how to configure MediatR in an ASP.NET Core application, including installing necessary NuGet packages and registering handlers and pre/post-processors. The guide concludes with examples of commands and queries, and a summary of MediatR's benefits.

Opinions

  • MediatR is a low-ambition library that solves a simple problem: decoupling the in-process sending of messages from handling messages.
  • MediatR supports intelligent dispatching via C# generic variance and a publisher/subscriber pattern.
  • The Mediator Pattern is used to reduce communication complexity between multiple objects or classes and supports easy maintenance of the code by loose coupling.
  • CQRS, or Command and Query Responsibility Segregation, is a pattern that separates read and update operations for a data store, maximizing an application's performance, scalability, and security.
  • MediatR has two kinds of messages: request/response messages, dispatched to a single handler, and notification messages, dispatched to multiple handlers.
  • MediatR has no dependencies and requires configuration of a single factory delegate used to instantiate all handlers, pipeline behaviors, and pre/post-processors.
  • MediatR helps to keep the Single Responsible Principle and is a simple mediator pattern implementation in .NET.

Use MediatR in ASP.NET or ASP.NET Core

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.

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

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.

View more from .NET Hub

Happy Coding!!!

Dotnet
Mediatr
Aspnetcore
Cqrs
Mediator Pattern
Recommended from ReadMedium