https://www.cnblogs.com/tanmingchao/p/9681975.html
本文转自
[1.MediatR 是什么?
![](https://img.haomeiwen.com/i686440/36ed276d2e7caa4d.gif)
](javascript:void(0); "复制代码")
<pre>微软官方eshopOnContainer开源项目中使用到了该工具,
mediatR 是一种中介工具,解耦了消息处理器和消息之间耦合的类库,支持跨平台 .net Standard和.net framework
https://github.com/jbogard/MediatR/wiki 这里是原文地址。其作者就是Automapper的作者。
功能要是简述的话就俩方面:
request/response 请求响应
pub/sub 发布订阅</pre>
[![](https://img.haomeiwen.com/i686440/9f1f604c9705bedf.gif)
](javascript:void(0); "复制代码")
2.****使用
<pre>nuget: install-package MediatR
MediatR没有其他的依赖项,您需要配置一个工厂委托,用来实例化所有处理程序、管道的行为,和前/后处理器。</pre>
[3.Autofac完整的IOC注入示例:
![](https://img.haomeiwen.com/i686440/f9729e82817422dc.gif)
](javascript:void(0); "复制代码")
<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>
![](https://img.haomeiwen.com/i686440/3fb912b491802d7c.gif)
](javascript:void(0); "复制代码")
[4.ASP.NET CORE 使用 IOC注入:
![](https://img.haomeiwen.com/i686440/091f289c5aeda44c.gif)
](javascript:void(0); "复制代码")
<pre>引用 MediatR nuget:install-package MediatR
引用IOC扩展 nuget:installpackage MediatR.Extensions.Microsoft.DependencyInjection
使用方式:
services.AddMediatR(typeof(MyHandler));
或
services.AddMediatR(typeof(Startup).GetTypeInfo().Assembly);
目的是为了扫描Handler的实现对象并添加到IOC的容器中</pre>
[![](https://img.haomeiwen.com/i686440/ae3afa5af6791d6f.gif)
](javascript:void(0); "复制代码")
5.参考示例
[5.1 请求响应(request/response),三步:
![](https://img.haomeiwen.com/i686440/87ddee0052f94ee6.gif)
](javascript:void(0); "复制代码")
<pre>步骤一:创建一个消息对象,需要实现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"</pre>
[![](https://img.haomeiwen.com/i686440/d08a877f192edc16.gif)
](javascript:void(0); "复制代码")
说明:如果某些情况下,如果你的消息发送不需要返回响应结果的话,可以使用AsyncRequestHandler<TRequest>
参考实现:
<pre>public class OneWay : IRequest { } public class OneWayHandlerWithBaseClass : AsyncRequestHandler<OneWay> { protected override Task Handle(OneWay request, CancellationToken cancellationToken) { // Twiddle thumbs } }</pre>
或者需要异步实现可以使用 RequestHandler
参考实现:
<pre>public class SyncHandler : RequestHandler<Ping, string> { protected override string Handle(Ping request) { return "Pong"; } }</pre>
[5.1.1 Request的类型说明,比较幼稚了,,
![](https://img.haomeiwen.com/i686440/40cc6c77e1d3f641.gif)
](javascript:void(0); "复制代码")
<pre>IRequest<T> 有返回值
IRequest 无返回值
IRequestHandler<T> 该对象的实现对象返回一个 Task 对象
AsyncRequestHandler<T> 该对象的子对象(继承)返回一个 Task 对象
RequestHandler<T> 该对象的子对象(继承) 无返回值
IRequestHandler<T,U> 该对象的实现对象返回一个 Task<U> 对象
RequestHandler<T,U> 该对象的子对象(继承)返回一个 U 对象</pre>
[![](https://img.haomeiwen.com/i686440/2a88bce49d3611ee.gif)
](javascript:void(0); "复制代码")
[5.2 Publishing,依旧三步走
![](https://img.haomeiwen.com/i686440/22951862a8f4b100.gif)
](javascript:void(0); "复制代码")
<pre>步骤一:创建一个用于通知的消息对象,实现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());</pre>
[![](https://img.haomeiwen.com/i686440/46eb4731e9a5a3c0.gif)
](javascript:void(0); "复制代码")
5.3 其他:见github作者wiki参考示例
分类: .NET
网友评论