ASP.NET Core MVC 入门到精通 - 3. 应用MediatR
环境:
- .NET 5
- ASP.NET Core MVC (project)
1. MediatR
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.另:中介者模式 - 定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合涣散,且能够独立地扭转它们之间的交互。中介者模式又叫调解模式,它是迪米特法令的典型利用。
2. 装置 & 配置
对于.NET5 (.net core), 应用nuget 装置MediatR.Extensions.Microsoft.DependencyInjection
.
配置:
public void ConfigureServices(IServiceCollection services){ services.AddControllersWithViews(); services.AddMediatR(typeof(Startup));}
3. MediatR音讯类型
3.1. Notifications 告诉模式
Notifications 告诉模式用于生产者发送告诉,消费者(能够多个)接管到告诉后,进行后续解决。
例:一个APS.NET 页面,拜访时,发送Notifications告诉;消费者简略记录收到告诉的工夫。
3.1.1. 定义基于INotification的告诉类
public class Ping : INotification { }
3.1.2. 定义消费者(关注告诉的解决办法)
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. 发送音讯告诉
// 基于dotnet core的依赖注入,注入IMediator对象private readonly IMediator _mediator;public HomeController(ILogger<HomeController> logger, IMediator mediator){ _logger = logger; _mediator = mediator;}public async Task<IActionResult> IndexAsync(){ // e.g. 拜访首页时,发送告诉 await _mediator.Publish(new Ping()); return View();}
3.1.4. 输入
Pong1, 5/27/2021 4:37:18 PMPong2, 5/27/2021 4:37:18 PM
3.2. Request/Response 申请响应模式
request/response用于命令和查问的场景。
3.2.1. 创立申请类:
public class RequestModel: IRequest<string>{}
3.2.2. 创立申请解决类
不同于告诉模式,request/response只能有一个申请解决。
public class RequestHandeler : IRequestHandler<RequestModel, string>{ public Task<string> Handle(RequestModel request, CancellationToken cancellationToken) { return Task.FromResult($"Pong {DateTime.Now}"); // 测试,返回内容给request }}
3.2.3. 页面中发送申请
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. 输入
Got response in controller: Pong 5/28/2021 2:04:26 PM
4. 总结
- MediatR是一种
过程内消息传递机制
。 - 反对以同步或异步的模式进行申请/响应,命令,查问(CQRS),告诉和事件的消息传递,并通过C#泛型反对音讯的智能调度。
- 其外围是音讯的解耦。
- 利用场景: 实现CQRS、EventBus等。
5. 参考 & 代码
- 参考: https://github.com/jbogard/MediatR
- 代码: https://github.com/jackniu81/dotnet/tree/main/MediatR-Demo