Using MediatR Request Handlers in ASP.NET Core to Decouple Code

Home

About

Articles

MediatR, by it’s definition, is a simple, unambitious mediator implementation in .NET . It was released in 2014 by Jimmy Bogard and is a useful package that can be used to implement the popular mediator pattern in .NET projects. It’s available on NuGet and is also open-source on GitHub .

This article isn’t meant to be an in-depth explanation of the mediator pattern, for that I’d recommend the series of articles over at .NET Core Tutorials beginning with The Mediator Pattern In .NET Core – Part 1 – What’s A Mediator? . Instead, I thought I’d demonstrate the advantages of using the MediatR package within a web application built using ASP.NET Core and C#, using request handlers to decouple code.

In this article I’ll be using a demo ASP.NET Core web application (available on GitHub ) that was originally built without using MediatR . This is to demonstrate the benefits of adding the mediator pattern into an existing project and how implementing MediatR request handlers can help decouple the code.

The demo ASP.NET Core web application contains the following projects:

MediatRApi (the API used for accepting GET, POST and PUT requests)

MediatRApi.Repositories (the repositories used for interacting with the database)

MediatRApi.Services (the services used throughout the application, such as the validation service)

In the controller that doesn’t use MediatR, you’ll notice the constructor is being injected with 4 dependencies ; 1 validation service as well as 3 repositories. However, if you notice in each of the action methods, only one repository is being used by each of them. Without using MediatR, this constructor is already a code smell:

Ideally, we want one dependency in the constructor of the controller: MediatR .

We’ll use the mediator pattern to decouple the code, creating separate “requests” that will store instructions for executing code in associated “request handlers” , with each request handler having it’s own set of dependencies.

I’ve added the new project MediatRApi.Handlers into the solution to store all our MediatR requests and request handlers that will be used to implement the mediator pattern in our ASP.NET Core web application:

You’ll need to add the MediatR NuGet package into your project to use the MediatR namespace:

Let’s explore each request and it’s associated request handler in this new project.

GetArtistRequest inherits from MediatR.IRequest and it’s response will be an Artist. The GetArtistHandler class inherits from MediatR.IRequestHandler and the dependencies being injected into it’s constructor are only used for retrieving an artist. The Handle method is used to execute the code and return the artist:

Similar to GetArtistRequest, the CreateAlbumRequest and CreateAlbumHandler inherit from MediatR.IRequest and MediatR.IRequestHandler and are responsible for creating an album and returning a guid:

Last but not least, SetRatingRequest and SetRatingHandler will set a rating for a song and return MediatR.Unit . MediatR.Unit represents a void type, since void isn’t a valid return type in C#:

To add MediatR as a dependency throughout our web application (i.e in the constructor of the controller) , we’ll need to register MediatR in the ‘ConfigureServices’ method within Startup.cs . To accomplish this we first need to add the Nuget package MediatR.Extensions.Microsoft.DependencyInjection into the project:

I’ve created a ‘Dependencies’ class with the one method ‘RegisterRequestHandlers’ that will be called from the ‘ConfigureServices’ method within the Startup.cs file of the web application:

Within the ‘ConfigureServices’ method of Startup.cs , ‘RegisterRequestHandlers’ is being called to inject MediatR into the web application and register the request handlers:

Let’s now see how this has helped to decouple our code in the web application!

In the new controller, there is now only one dependency: MediatR. Each of the action methods will initialize a new request and send it off to MediatR to be handled by it’s associated request handler:

Thank you for reading this article! The full solution used in this guide is available at github.com/kiltandcode/mediatr-demo

Have you ever wondered if you could use the .NET CLI and Visual Studio Code to build a new .NET application, instead of relying on Visual Studio to do all of the heavy lifting? Read more

Back in 2019 I wrote an article on Best Practices for Writing Unit Tests in C# for Bulletproof Code. This has become one of my more popular articles, and despite it approaching 2 years old, the best practices mentioned are still relevant today. I touched upon the popular mocking framework Moq, bu... Read more

As a keen Spotify user that is always in search of new albums and artists to listen to, I was particularly interested when I heard that Rolling Stone magazine announced a new, updated list of their 500 Greatest Albums of All Time for 2020. Read more

RSS