MediatR基本使用

开源地址:https://github.com/jbogard/MediatR
依赖注入:https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection

1、NuGet添加引用包 MediatR.Extensions.Microsoft.DependencyInjection

2、依赖注入相关服务

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

3、MediatR会分派两种消息
a.单播:请求/响应消息,分派给单个处理程序
b.多播:通知消息,分派给多个处理程序

4、单播的消息

a.定义消息类型,继承MediatR.IRequest接口的消息类
  IRequest<T>:有返回值单播消息
  IRequest 无返回值单播消息

public class Ping : IRequest<string>  
{ 
  //可以自定义任意的字段
  public string Title { get; set; }   
  public string Content { get; set; } 
}

b.创建处理消息的类,继承IRequestHandler<Ping, string>: 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");
   }
}

c.使用中介者发送单播消息

  IMediator mediator = context.RequestServices.GetRequiredService<IMediator>(); //可以使用依赖注入的方式获得mediator
  Ping ping = new Ping() { Title = "TestTitle" };
  string result = await mediator.Send(ping);
  await context.Response.WriteAsync(result);

5.多播消息
a.定义多播消息类,需要继承INotification

public class NotyPing : INotification
{
    public string Message { get; set; }
}

b.定义一个或多个处理消息类

public class Noty1Handler : INotificationHandler<NotyPing>  
{
    public Task Handle(NotyPing notification, CancellationToken cancellationToken)
    {
        Console.WriteLine("Noty1Handler Doing..."+notification.Message);
        return Task.CompletedTask;
    }
}

public class Noty2Handler : INotificationHandler<NotyPing>
{
    public Task Handle(NotyPing notification, CancellationToken cancellationToken)
    {
        Console.WriteLine("Noty2Handler Doing..." + notification.Message);
        return Task.CompletedTask;
    }
}

c.发布消息

IMediator mediator = context.RequestServices.GetRequiredService<IMediator>();
NotyPing notyPing = new NotyPing { Message = "Test Noty" };
await mediator.Publish(notyPing);

d.多路广播发布策略问题

Publish 方法的默认实现:同步循环每个处理程序,一个失败不影响后边的处理程序,这样可以确保每个处理程序都依次运行,而且按照顺序运行。

根据发布通知的不同需求,您可能需要不同的策略来处理通知,也许您想并行发布所有通知,或者使用您自己的异常处理逻辑包装每个通知处理程序。

MediatR.Examples.PublishStrategies 中可以找到一些示例实现, 其实就是使用 PublishStrategy 枚举设置不同的策略,参考以下链接。

6.类型协变(单播处理器和多播处理器)
例如:您可以实现 INotificationHandler <INotification> 来处理所有通知

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值