How to use MediatR in ASP.NET Core

By FoxLearn 1/7/2025 7:08:58 AM   19
MediatR is an open-source implementation of the mediator design pattern, which helps manage communication between objects.

Instead of objects interacting directly, they communicate through a mediator, reducing dependencies and simplifying management.

To use MediatR in ASP.Net Core, first install the following NuGet packages: MediatR and MediatR.Extensions.Microsoft.DependencyInjection. This can be done through the NuGet Package Manager or the NuGet Package Manager Console in Visual Studio.

Configure MediatR in ASP.NET Core

After successfully installing the two packages in your project, the next step is to configure MediatR in the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMediatR(typeof(Startup));
}

Using MediatR to handle notification events in ASP.NET Core

MediatR supports two types of messages: request/response and notification. In this example, we will focus on using MediatR to handle notification events.

First, create a class that implements the INotification interface from Mediat

public class NotificationEvent : INotification
{
    public string Message { get; }
    public NotificationEvent(string message)
    {
        Message = message;
    }
}

Next, create handlers for this event by implementing the INotificationHandler interface.

public class FileNotificationHandler : INotificationHandler<NotificationEvent>
{
    public Task Handle(NotificationEvent notification, CancellationToken cancellationToken)
    {
        string message = notification.Message;
        LogToFile(message);
        return Task.CompletedTask;
    }

    private void LogToFile(string message)
    {
        // Code to log the message to a text file
    }
}

public class DatabaseNotificationHandler : INotificationHandler<NotificationEvent>
{
    public Task Handle(NotificationEvent notification, CancellationToken cancellationToken)
    {
        string message = notification.Message;
        LogToDatabase(message);
        return Task.CompletedTask;
    }

    private void LogToDatabase(string message)
    {
        // Code to log the message to a database
    }
}

Now, integrate MediatR into your ASP.Net Core project using dependency injection. 

For example, how to inject the IMediator instance into a controller using constructor injection:

public class NotificationsController : ControllerBase
{
    private readonly IMediator _mediator;

    public NotificationsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    // Controller methods go here
}

Finally, you can publish events from your controller methods like this:

_mediator.Publish(new NotificationEvent("Event occurred"));

This call to Publish will trigger the Handle methods of both the FileNotificationHandler and DatabaseNotificationHandler.

The mediator design pattern is a behavioral pattern that encapsulates how objects within a group interact with each other. MediatR is an implementation of this pattern that helps decouple command/query/event-handling code.