其他分享
首页 > 其他分享> > 中介者模式的实现-MediatR

中介者模式的实现-MediatR

作者:互联网

简介

微软官方的开源项目eShopOnContainers中,用到了一个实现中介者模式的类库:MediatR。
他是一个低调的类库,致力于解决一个简单的问题:解耦进程内消息的发送与处理。
中介者模式的定义为:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互应用,从而使其耦合松散,而且可以独立地改变他们之间的交互。
开源地址:https://github.com/jbogard/MediatR

MediatR支持两种模式:

请求/响应模式:请求/响应模式,也可以叫做命令模式,主要适用于命令和查询场景。一个请求只能被一个处理者捕获,如果存在多个处理者,那么只有最后一个处理者会被激活。
发布模式:一般用于发布一个事件,通知订阅者某件事情已经发生,对此事感兴趣的订阅者可以采取行动了。一般是一个发布这,多个订阅者。

基本使用

1、NuGet添加引用包 MediatR.Extensions.Microsoft.DependencyInjection
2、注入相关服务

services.AddMediatR(System.Reflection.Assembly.GetExecutingAssembly());//把自定义的消息类,处理消息类注入到服务中

请求/响应模式:

定义消息类型

IRequest:有返回值单播消息
IRequest 无返回值单播消息

public class Ping : IRequest<string>  { 
  public string Title { get; set; }   
  public string Content { get; set; } }

创建消息处理类

IRequestHandler<Ping, string>: Ping消息类,string是返回类型
RequestHandler<Ping,string>:如果是同步处理,可继承此类
AsyncRequestHandler<Ping,string>:如果是异步处理,可继承此类(测试没找到这个类)

public class PingHandler : IRequestHandler<Ping, string>
{
  public Task<string> Handle(Ping request, CancellationToken cancellationToken)
   {
    Console.WriteLine("PingHandler Doing..." + request.Title);
    return Task.FromResult("ok");
   }
}

发送请求:

 public IActionResult Index([FromServices] IMediator mediat)
        {
           Task<string> task = mediat.Send(new Ping { Title = "testTitle" });
            string result = task.Result;
            return View();
        }

发布模式

INotification:消息类继承此接口
INotificationHandler:消息处理类继承此接口

    public class NotifiMessage : INotification
    {
        public string Title { get; set; }
    }
    public class NotifiHandler1 : INotificationHandler<NotifiMessage>
    {
        public async Task Handle(NotifiMessage notification, CancellationToken cancellationToken)
        {
            await Task.Delay(3000);
            Console.WriteLine($"{notification.Title}1,{Thread.CurrentThread.ManagedThreadId}");
        }
    }
    public class NotifiHandler2 : INotificationHandler<NotifiMessage>
    {
        public async Task Handle(NotifiMessage notification, CancellationToken cancellationToken)
        {
            await Task.Delay(3000);
            Console.WriteLine($"{notification.Title}2,{Thread.CurrentThread.ManagedThreadId}");
        }
    }

发布消息:

await mediator.Publish(new Hello() {MsgId = 300});

参考:
http://www.csharpkit.com/en/2018-04-19_78780.html
https://www.jianshu.com/p/583bcba352ec(待)

标签:Task,MediatR,Title,模式,中介,public,string
来源: https://www.cnblogs.com/fanfan-90/p/14237052.html