joydip_kanjilal
Contributor

How to use MediatR in ASP.Net Core

how-to
May 20, 20194 mins
C#Microsoft .NETSoftware Development

Take advantage of MediatR and the mediator design pattern to reduce the dependencies between objects in your ASP.Net Core applications

MediatR is an open source project and an implementation of the mediator design pattern. The mediator design pattern controls how a set of objects communicate and helps to reduce the number of dependencies among these objects that you must manage. In the mediator design pattern, objects don’t communicate with one another directly, but through a mediator. This article presents a discussion of how we can use MediatR in ASP.Net Core applications.

Create an ASP.Net Core project in Visual Studio

First off, let’s create an ASP.Net Core project in Visual Studio. Assuming Visual Studio 2017 or Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.Net Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.Net Core Web Application” from the list of templates displayed.
  4. Click Next. 
  5. In the “Configure your new project” window that is shown next, specify the name and location for the new project.
  6. Click Create. 
  7. A new window “Create New ASP.Net Core Web Application” is shown next.
  8. Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
  9. Select “Web Application” as the project template.
  10. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  11. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  12. Click Create. 

This will create a new ASP.Net Core project in Visual Studio. We’ll use this project in the subsequent sections of this article to implement our mediator pattern with MediatR.

Install MediatR in your ASP.Net Core project

Using MediatR in ASP.Net Core is straightforward. At the time of this writing the current version of MediatR is 7.0.0. Assuming you have created an ASP.Net Core project in Visual Studio, the next step is installing the following NuGet packages.

  • MediatR
  • MediatR.Extensions.Microsoft.DependencyInjection

To do that, you can either use the NuGet Package Manager or the NuGet Package Manager Console.

Configure MediatR in ASP.Net Core

Once the two packages mentioned in the earlier section have been successfully installed in your project, the next step is to configure MediatR in the Startup class. To do this, you should write the following code in the ConfigureServices method. Note that the ConfigureServices method is used to add services at runtime to the container.

public void ConfigureServices(IServiceCollection services)
 {
    services.AddMediatR(typeof(Startup));
    services.AddMvc().SetCompatibilityVersion
    (CompatibilityVersion.Version_2_2);
 }

Use MediatR to handle notification events in ASP.Net Core

MediatR provides support for two types of messages: request/response and notification. In this example, we’ll examine how we can use MediatR to handle notification events.

Now, create a class that extends the INotification interface of MediatR as shown below.

public class LogEvent : INotification
    {
        public string message;
        public LogEvent(string message)
        {
            this.message = message;
        }
    }

To create handlers for this event, you should create classes that implement the INotificationHandler interface as shown below.

public class FileNotificationHandler : INotificationHandler<LogEvent>
    {
        public Task Handle(LogEvent notification,
        CancellationToken cancellationToken)
        {
            string message = notification.message;
            Log(message);
            return Task.FromResult(0);
        }
        private void Log(string message)
        {
            //Write code here to log message(s) to a text file
        }
    }

public class DBNotificationHandler : INotificationHandler<LogEvent>
    {
        public Task Handle(LogEvent notification,
        CancellationToken cancellationToken)
        {
            string message = notification.message;
            Log(message);
            return Task.FromResult(0);
        }
        private void Log(string message)
        {
            //Write code here to log message(s) to the database
        }
    }

Use dependency injection to inject an IMediator instance in ASP.Net Core

So far so good. We have two handlers for the LogEvent we created earlier. Next we’ll take advantage of dependency injection. The following code snippet shows how we can inject an IMediator instance using constructor injection.

public class ValuesController : ControllerBase
    {
        private readonly IMediator _mediator;
                public ValuesController(IMediator mediator)
        {
            this._mediator = mediator;
        }
      //Write your controller methods here
    }

Lastly, you can use the following code to publish events from your controller methods.

_mediator.Publish(new LogEvent("Hello World"));

The call to the Publish method will call the Handle method of the DBNotificationHandler and the FileNotificationHandler classes.

The mediator design pattern is a behavioral pattern that defines an object that encapsulates how a group of objects interact with one another. MediatR is an implementation of the mediator design pattern that helps you to decouple your command/query/event-handling code. I will demonstrate how we can use MediatR to handle request/response messages in a future post here.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author