A brief introduction to MediatR in .NET
Tags: csharp, mediatr, dotnet, dotnetcore
Published: 2023-05-21 16:02:17

MediatR is a popular open-source package for implementing the mediator pattern in .NET applications. It provides a simple way to separate the concerns of your application’s components by routing requests and responses through a mediator. In this article, we’ll explore how to install and use the MediatR package in .NET applications with code examples.

You could support the project here:
[https://github.com/jbogard/MediatR](https://github.com/jbogard/MediatR)

**Installing MediatR Package**
To install MediatR, we can use the NuGet Package Manager in Visual Studio or the .NET CLI. In this example, we’ll use the .NET CLI.

First, navigate to the root directory of your .NET application in the command prompt. Then, run the following command:

```
dotnet add package MediatR
```
This will install the latest version of the MediatR package in your .NET application.

**Using MediatR Package**
To use the MediatR package, we need to create a mediator and define the requests and handlers.

**Creating a Mediator**
To create a mediator, we need to register the MediatR services in the dependency injection container. In this example, we’ll use the default Microsoft dependency injection container.

First, add the following line of code to the `ConfigureServices `method in the `Startup.cs` file:

```csharp
services.AddMediatR(typeof(Startup));
```
This will register the MediatR services in the dependency injection container and allow us to use the `IMediator` interface to send requests.

**Defining Requests and Handlers**
Requests in MediatR represent the input to the mediator. Handlers represent the logic for processing the requests. To define a request and its handler, we need to create two classes: a request class and a handler class.

First, let’s create a request class. In this example, we’ll create a simple request to get a list of products:
```csharp
public class GetProductListQuery : IRequest<List<Product>>
{
}
```
This request class inherits from the `IRequest<TResponse> `interface, where `TResponse` is the type of the response we expect from the handler.

Next, let’s create a handler class to process the request. In this example, we’ll create a handler that returns a list of hardcoded products:
```csharp
public class GetProductListHandler : IRequestHandler<GetProductListQuery, List<Product>>
{
    public Task<List<Product>> Handle(GetProductListQuery request, CancellationToken cancellationToken)
    {
        List<Product> productList = new List<Product>()
        {
            new Product() { Id = 1, Name = "Product 1" },
            new Product() { Id = 2, Name = "Product 2" },
            new Product() { Id = 3, Name = "Product 3" },
        };

        return Task.FromResult(productList);
    }
}
```
This handler class implements the `IRequestHandler<TRequest, TResponse>` interface, where `TRequest` is the type of the request and `TResponse` is the type of the response.

**Sending Requests**
To send a request to the mediator, we can use the `IMediator` interface. In this example, we'll send a request to get a list of products and display the results in the console:
```csharp
public class ProductService
{
    private readonly IMediator mediator;

    public ProductService(IMediator mediator)
    {
        this.mediator = mediator;
    }

    public async Task GetProductList()
    {
        var productList = await mediator.Send(new GetProductListQuery());
        foreach (var product in productList)
        {
            Console.WriteLine(product.Name);
        }
    }
}
```
This code creates a `ProductService` class that accepts an `IMediator` interface in the constructor. The `GetProductList` sends a request to Mediatr with query params and accepts the results.