ASP.NET Core MVC 入门到精通 - 3. 使用MediatR
环境:
- .NET 5
- ASP.NET Core MVC (project)
MediatR .NET中的简单中介者模式实现,一种进程内消息传递机制
(无其他外部依赖)。支持以同步或异步的形式进行请求/响应,命令,查询,通知和事件的消息传递,并通过C#泛型支持消息的智能调度。
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.
另:中介者模式 - 定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。中介者模式又叫调停模式,它是迪米特法则的典型应用。
对于.NET5 (.net core), 使用nuget 安装MediatR.Extensions.Microsoft.DependencyInjection
.
配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddMediatR(typeof(Startup));
}
Notifications 通知模式用于生产者发送通知,消费者(可以多个)接收到通知后,进行后续处理。
例:一个APS.NET 页面,访问时,发送Notifications通知;消费者简单记录收到通知的时间。
public class Ping : INotification { }
public class Pong1 : INotificationHandler
{
public Task Handle(Ping notification, CancellationToken cancellationToken)
{
Debug.WriteLine($"Pong1, {DateTime.Now}");
return Task.CompletedTask;
}
}
public class Pong2 : INotificationHandler
{
public Task Handle(Ping notification, CancellationToken cancellationToken)
{
Debug.WriteLine($"Pong2, {DateTime.Now}");
return Task.CompletedTask;
}
}
// 基于dotnet core的依赖注入,注入IMediator对象
private readonly IMediator _mediator;
public HomeController(ILogger logger, IMediator mediator)
{
_logger = logger;
_mediator = mediator;
}
public async Task IndexAsync()
{
// e.g. 访问首页时,发送通知
await _mediator.Publish(new Ping());
return View();
}
Pong1, 5/27/2021 4:37:18 PM
Pong2, 5/27/2021 4:37:18 PM
request/response用于命令和查询的场景。
public class RequestModel: IRequest<string>
{
}
不同于通知模式,request/response只能有一个请求处理。
public class RequestHandeler : IRequestHandler<RequestModel, string>
{
public Task<string> Handle(RequestModel request, CancellationToken cancellationToken)
{
return Task.FromResult($"Pong {DateTime.Now}"); // 测试,返回内容给request
}
}
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();
}
Got response in controller: Pong 5/28/2021 2:04:26 PM
进程内消息传递机制
。