MediatR是什么?2019-09-25

https://www.cnblogs.com/tanmingchao/p/9681975.html
本文轉(zhuǎn)自

1.MediatR 是什么?

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre>微軟官方eshopOnContainer開源項(xiàng)目中使用到了該工具,

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

https://github.com/jbogard/MediatR/wiki 這里是原文地址。其作者就是Automapper的作者。
功能要是簡(jiǎn)述的話就倆方面:

request/response 請(qǐng)求響應(yīng)

pub/sub 發(fā)布訂閱</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

2.****使用

<pre>nuget: install-package MediatR

MediatR沒有其他的依賴項(xiàng),您需要配置一個(gè)工廠委托,用來實(shí)例化所有處理程序、管道的行為,和前/后處理器。</pre>

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

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre>// 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</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

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

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre>引用 MediatR nuget:install-package MediatR

引用IOC擴(kuò)展 nuget:installpackage MediatR.Extensions.Microsoft.DependencyInjection

使用方式:

services.AddMediatR(typeof(MyHandler));

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

目的是為了掃描Handler的實(shí)現(xiàn)對(duì)象并添加到IOC的容器中</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

5.參考示例

5.1 請(qǐng)求響應(yīng)(request/response),三步:

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre>步驟一:創(chuàng)建一個(gè)消息對(duì)象,需要實(shí)現(xiàn)IRequest,或IRequest<>接口,表明該對(duì)象是處理器的一個(gè)對(duì)象 public class Ping : IRequest<string> { }

步驟二:創(chuàng)建一個(gè)處理器對(duì)象 public class PingHandler : IRequestHandler<Ping, string> { public Task<string> Handle(Ping request, CancellationToken cancellationToken) { return Task.FromResult("Pong"); } }

步驟三:最后,通過mediator發(fā)送一個(gè)消息 var response = await mediator.Send(new Ping()); Debug.WriteLine(response); // "Pong"</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

說明:如果某些情況下,如果你的消息發(fā)送不需要返回響應(yīng)結(jié)果的話,可以使用AsyncRequestHandler<TRequest>

參考實(shí)現(xiàn):

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

或者需要異步實(shí)現(xiàn)可以使用 RequestHandler

參考實(shí)現(xiàn):

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

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

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre>IRequest<T> 有返回值

IRequest 無返回值

IRequestHandler<T> 該對(duì)象的實(shí)現(xiàn)對(duì)象返回一個(gè) Task 對(duì)象

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

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

IRequestHandler<T,U> 該對(duì)象的實(shí)現(xiàn)對(duì)象返回一個(gè) Task<U> 對(duì)象

RequestHandler<T,U> 該對(duì)象的子對(duì)象(繼承)返回一個(gè) U 對(duì)象</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

5.2 Publishing,依舊三步走

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

<pre>步驟一:創(chuàng)建一個(gè)用于通知的消息對(duì)象,實(shí)現(xiàn)INotification接口 public class Ping : INotification { }

步驟二:創(chuàng)建通知的處理器對(duì)象 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發(fā)布你的消息 await mediator.Publish(new Ping());</pre>

[
復(fù)制代碼

](javascript:void(0); "復(fù)制代碼")

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

分類: .NET

標(biāo)簽: .NET, MediatR, 開發(fā)記錄

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 3,988評(píng)論 0 11
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程,因...
    小菜c閱讀 7,292評(píng)論 0 17
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,618評(píng)論 1 32
  • 23種設(shè)計(jì)模式總結(jié) 1.單例模式(Singleton Pattern) 定義:Ensure a class has...
    Mo_ham_med閱讀 309評(píng)論 0 0
  • 2017的大事情在原先既定的軌道上行進(jìn),希望接下來的置換也希望順順當(dāng)當(dāng)?shù)?...
    mo清夜無塵閱讀 246評(píng)論 0 0

友情鏈接更多精彩內(nèi)容