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> 來處理所有通知
 
7.參考資料
MediatR Document WIKI   https://github.com/jbogard/MediatR/wiki
ASP.NET Core 使用 MediatR進 程內發布與訂閱   https://www.cnblogs.com/guokun/p/11001052.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM