Take advantage of MediatR and the mediator design pattern to reduce the dependencies between objects in your ASP.Net Core applications Credit: Wanita di Indonesia 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. Launch the Visual Studio IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.Net Core Web Application” from the list of templates displayed. Click Next. In the “Configure your new project” window that is shown next, specify the name and location for the new project. Click Create. A new window “Create New ASP.Net Core Web Application” is shown next. Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top. Select “Web Application” as the project template. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either. 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. Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos