DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

Decoupling Communication with MediatR

MediatR is a library that implements the Mediator pattern, facilitating communication between different parts of an application without them being directly coupled. This promotes a more modular and flexible design. It is widely used in applications to manage commands and events in a centralized way. In this example, we will see how to use MediatR to send a command and process its response in a handler.

Libraries:

To use the MediatR and Microsoft.Extensions.DependencyInjection libraries, install the following NuGet packages in your project:

Install-Package MediatR.Extensions.Microsoft.DependencyInjection
Install-Package Microsoft.Extensions.DependencyInjection
Enter fullscreen mode Exit fullscreen mode

Example Code:

using MediatR;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading;
using System.Threading.Tasks;

// Defining the command
public class GreetCommand : IRequest<string>
{
    public string Name { get; set; }
}

// Defining the handler for the command
public class GreetCommandHandler : IRequestHandler<GreetCommand, string>
{
    public Task<string> Handle(GreetCommand request, CancellationToken cancellationToken)
    {
        return Task.FromResult($"Hello, {request.Name}!");
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        // Configuring MediatR with dependency injection
        var services = new ServiceCollection();
        services.AddMediatR(typeof(Program));
        services.AddSingleton<GreetCommandHandler>(); // Registering the handler

        var provider = services.BuildServiceProvider();

        var mediator = provider.GetRequiredService<IMediator>();

        // Sending the command and receiving the response
        var result = await mediator.Send(new GreetCommand { Name = "Developer" });
        Console.WriteLine(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we create a command called GreetCommand that contains a Name field. The handler GreetCommandHandler receives this command and returns a personalized greeting. In the Main method, we configure MediatR using dependency injection and register the handler. We create the command with the name “Developer” and send it via MediatR. The handler processes the command and returns the greeting, which is displayed in the console.

Conclusion:

MediatR is a powerful tool for implementing the Mediator pattern, decoupling business logic from communication between components. It helps organize your application better, making it easier to maintain and test.

Source code: GitHub

Top comments (0)