NET Core MVC to master – 3. Use Mediatr

Environment:

  • .NET 5
  • ASP.NET Core MVC (project)

1. MediatR

Simple Mediator pattern implementation in MediaTr.Net, an in-process messaging mechanism (with no other external dependencies). Support for synchronous or asynchronous messaging of requests/responses, commands, queries, notifications, and events, and intelligent scheduling of messages through C# generics.

Simple mediator implementation in .NET

In-process messaging with no dependencies.

Supports request/response, commands, queries, notifications and events, synchronous and async with intelligent dispatching via C# generic variance.

Also: Mediator pattern – Defines a mediation object that encapsulates the interactions between a set of objects, loosens the coupling between the original objects, and can change the interactions between them independently. The mediator model, also known as the mediation model, is a typical application of Demeter’s Law.

2. Installation & configuration

For. NET5 (.net core), use nuget install MediatR. Extensions. Microsoft. DependencyInjection.

Configuration:

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

3. Mediatr message type

3.1. Notifications mode

The Notifications notification mode is used by a producer to send a notification, which can be received by a consumer (multiple) for subsequent processing. Example: An APS.net page that sends Notifications when accessed; The consumer simply records when the notification is received.

3.1.1. Define notification class based on INotification

public class Ping : INotification { }

3.1.2. Defining consumers (handling of notifications of concern)

public class Pong1 : INotificationHandler<Ping> { public Task Handle(Ping notification, CancellationToken cancellationToken) { Debug.WriteLine($"Pong1, {DateTime.Now}"); return Task.CompletedTask; } } public class Pong2 : INotificationHandler<Ping> { public Task Handle(Ping notification, CancellationToken cancellationToken) { Debug.WriteLine($"Pong2, {DateTime.Now}"); return Task.CompletedTask; }}

3.1.3. Send Message Notification

IMediator private readonly iMediator _mediator (private readonly iMediator); public HomeController(ILogger<HomeController> logger, IMediator mediator) { _logger = logger; _mediator = mediator; } public async Task<IActionResult> IndexAsync() { // e.g. Publish(new Ping()); await await await await await await await await await await await await await await await await await await await await await await await return View(); }

3.1.4. Output

Pong1, 5/27/2021 4:37:18 PM
Pong2, 5/27/2021 4:37:18 PM

3.2. Request/Response mode

Request/Response scenarios for commands and queries.

3.2.1. Creating a Request Class:

public class RequestModel: IRequest<string>
{
}

3.2.2. Create the request handling class

Unlike notification mode, request/response can only have one request processed.

public class RequestHandeler : IRequestHandler<RequestModel, string> { public Task<string> Handle(RequestModel request, CancellationToken cancellationToken) { return Task.FromResult($"Pong {DateTime.Now}"); // test, return content to request}}

3.2.3. Send a request in the page

private readonly ILogger<HomeController> _logger;
private readonly IMediator _mediator;

public HomeController(ILogger<HomeController> logger, IMediator mediator)
{
    _logger = logger;
    _mediator = mediator;
}

public async Task<IActionResult> IndexAsync()
{
    // send request, and show Response
    var response = await _mediator.Send(new RequestModel());
    Debug.WriteLine("Got response in controller: " +response);

    return View();
}

3.2.4. The output

Got response in controller: Pong 5/28/2021 2:04:26 PM

4. To summarize

  • MediatR is aIntra-process messaging mechanism.
  • Support synchronous or asynchronous messaging of requests/responses, commands, queries (CQRS), notifications, and events, and intelligent scheduling of messages through C# generics.
  • At its core is decoupling of messages.
  • Application scenario: realize CQRS, EventBus, etc.

5. Reference & Code

  • Reference: https://github.com/jbogard/MediatR
  • Code: https://github.com/jackniu81/dotnet/tree/main/MediatR-Demo