MediatR


1.MediatR是什么?

微軟官方eshopOnContainer開源項目中使用到了該工具,

mediatR 是一種中介工具,解耦了消息處理器和消息之間耦合的類庫,支持跨平台 .net Standard和.net framework

https://github.com/jbogard/MediatR/wiki 這里是原文地址。其作者就是Automapper的作者。

功能要是簡述的話就倆方面:

request/response 請求響應

pub/sub 發布訂閱

 

2.使用

nuget: install-package MediatR

MediatR沒有其他的依賴項,您需要配置一個工廠委托,用來實例化所有處理程序、管道的行為,和前/后處理器。

 

3.Autofac完整的IOC注入示例:

// uncomment to enable polymorphic dispatching of requests, but note that // this will conflict with generic pipeline behaviors // builder.RegisterSource(new ContravariantRegistrationSource()); // mediator itself
builder .RegisterType<Mediator>() .As<IMediator>() .InstancePerLifetimeScope(); // request handlers
builder .Register<SingleInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => c.TryResolve(t, out var o) ? o : null; }) .InstancePerLifetimeScope(); // notification handlers
builder .Register<MultiInstanceFactory>(ctx => { var c = ctx.Resolve<IComponentContext>(); return t => (IEnumerable<object>)c.Resolve(typeof(IEnumerable<>).MakeGenericType(t)); }) .InstancePerLifetimeScope(); // finally register our custom code (individually, or via assembly scanning) // - requests & handlers as transient, i.e. InstancePerDependency() // - pre/post-processors as scoped/per-request, i.e. InstancePerLifetimeScope() // - behaviors as transient, i.e. InstancePerDependency()
builder.RegisterAssemblyTypes(typeof(MyType).GetTypeInfo().Assembly).AsImplementedInterfaces(); // via assembly scan //builder.RegisterType<MyHandler>().AsImplementedInterfaces().InstancePerDependency(); // or individually

 

4.ASP.NET CORE 使用 IOC注入:

引用 MediatR nuget:install-package MediatR

引用IOC擴展 nuget:installpackage MediatR.Extensions.Microsoft.DependencyInjection

使用方式:

services.AddMediatR(typeof(MyHandler));

或

services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);

目的是為了掃描Handler的實現對象並添加到IOC的容器中

 

5.參考示例

5.1 請求響應(request/response),三步:

步驟一:創建一個消息對象,需要實現IRequest,或IRequest<>接口,表明該對象是處理器的一個對象

public class Ping : IRequest<string> { }

步驟二:創建一個處理器對象

public class PingHandler : IRequestHandler<Ping, string> { public Task<string> Handle(Ping request, CancellationToken cancellationToken) { return Task.FromResult("Pong"); } }

步驟三:最后,通過mediator發送一個消息

var response = await mediator.Send(new Ping()); Debug.WriteLine(response); // "Pong"

 

 

說明:如果某些情況下,如果你的消息發送不需要返回響應結果的話,可以使用AsyncRequestHandler<TRequest>

參考實現:

public class OneWay : IRequest { } public class OneWayHandlerWithBaseClass : AsyncRequestHandler<OneWay> { protected override Task Handle(OneWay request, CancellationToken cancellationToken) { // Twiddle thumbs } }

 

 

或者需要異步實現可以使用 RequestHandler 

參考實現:

public class SyncHandler : RequestHandler<Ping, string> { protected override string Handle(Ping request) { return "Pong"; } }

 

 

5.1.1 Request的類型說明,比較幼稚了,,

IRequest<T> 有返回值

IRequest 無返回值

 

IRequestHandler<T> 該對象的實現對象返回一個 Task 對象

AsyncRequestHandler<T> 該對象的子對象(繼承)返回一個 Task 對象

RequestHandler<T> 該對象的子對象(繼承) 無返回值

 

IRequestHandler<T,U> 該對象的實現對象返回一個 Task<U> 對象

RequestHandler<T,U> 該對象的子對象(繼承)返回一個 U 對象

 

5.2 Publishing,依舊三步走

步驟一:創建一個用於通知的消息對象,實現INotification接口

public class Ping : INotification { }

步驟二:創建通知的處理器對象

public class Pong1 : INotificationHandler<Ping> { 
  
  public Task Handle(Ping notification, CancellationToken cancellationToken) { Debug.WriteLine("Pong 1"); return Task.CompletedTask; } }

  public class Pong2 : INotificationHandler<Ping> { public Task Handle(Ping notification, CancellationToken cancellationToken) { Debug.WriteLine("Pong 2"); return Task.CompletedTask; } } 三步驟:最終使用mediator發布你的消息 await mediator.Publish(new Ping());

 

 

5.3 其他:見github作者wiki參考示例

 

 

 

 

 

 


免責聲明!

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



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