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 What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos