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 feature 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos