惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog
V
Vulnerabilities – Threatpost
Apple Machine Learning Research
Apple Machine Learning Research
V
V2EX
博客园 - 叶小钗
阮一峰的网络日志
阮一峰的网络日志
人人都是产品经理
人人都是产品经理
Latest news
Latest news
博客园 - 三生石上(FineUI控件)
美团技术团队
aimingoo的专栏
aimingoo的专栏
Google Online Security Blog
Google Online Security Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threatpost
Y
Y Combinator Blog
T
Tailwind CSS Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
A
Arctic Wolf
C
Cyber Attacks, Cyber Crime and Cyber Security
小众软件
小众软件
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
Tenable Blog
W
WeLiveSecurity
L
LINUX DO - 热门话题
D
Docker
Cyberwarzone
Cyberwarzone
量子位
A
About on SuperTechFans
The Last Watchdog
The Last Watchdog
雷峰网
雷峰网
C
CERT Recently Published Vulnerability Notes
P
Palo Alto Networks Blog
The Hacker News
The Hacker News
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Full Disclosure
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
T
The Exploit Database - CXSecurity.com
Engineering at Meta
Engineering at Meta
O
OpenAI News
Hacker News - Newest:
Hacker News - Newest: "LLM"
Scott Helme
Scott Helme
IT之家
IT之家
S
Secure Thoughts
MongoDB | Blog
MongoDB | Blog
L
Lohrmann on Cybersecurity
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News

博客园 - Jack Niu

最简单的判断是否为IE浏览器的方法 - document.documentMode “Microsoft.Build.Tasks.Xaml.PartialClassGenerationTask“ task could not be loaded from the assembly ASP.NET Core MVC 入门到精通 - 1. 开发必备工具 (2021) 算法 - 计算汉明距离 浏览器(Cache)的缓存逻辑(HTTP条件请求) 算法: 合并两个有序链表 前端进阶(2)使用fetch/axios时, 如何取消http请求 前端进阶(1)Web前端性能优化 2021 Top 100 C#/.NET Interview Questions And Answers 安装umi后,使用umi提示不是内部或者外部命令 解决国内不能访问github的问题 (算法) - 不使用递归,实现斐波那契数列 2021 .NET/dotnet Core/C# 面试题及参考答案 2021 Vue.js 面试题汇总及答案 CSS3 Flex Box 弹性盒子、弹性布局 Angular入门到精通系列教程(15)- 目录结构(工程结构)推荐 Angular入门到精通系列教程(14)- Angular 编译打包 & Docker发布 Angular入门到精通系列教程(13)- 路由守卫(Route Guards) Angular入门到精通系列教程(12)- 路由(Routing) Angular入门到精通系列教程(11)- 模块(NgModule),延迟加载模块
ASP.NET Core MVC 入门到精通 - 3. 使用MediatR
Jack Niu · 2021-05-28 · via 博客园 - Jack Niu

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.

另:中介者模式 - 定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。中介者模式又叫调停模式,它是迪米特法则的典型应用。

2. 安装 & 配置

对于.NET5 (.net core), 使用nuget 安装MediatR.Extensions.Microsoft.DependencyInjection.

配置:

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

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 PM
Pong2, 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. 参考 & 代码