本文转载请联系码农阅读公众号。MediatR是调解器模式的.NET开源实现。中介者模式控制了一组对象之间的相互通信,有效地降低了对象之间错综复杂的相互依赖关系。在中介者模式下,一个对象不需要直接与另一个对象进行通信,而是通过一个中介者来传达。本文将讨论如何在ASP.NetCore中使用MediatR。安装MediatR在ASP.NetCore中使用MediatR非常简单,只需要通过Nuget安装以下两个包即可。MediatRMediatR.Extensions.Microsoft.DependencyInjection最新版本为9.0.0,如下图所示:配置MediatR项目中安装完以上两个Nuget包后,就可以在Startup类中配置MediatR了。方法是在ConfigureServices()方法中将MediaR注入到IServiceCollection容器中,如下代码所示:;}使用MediaR处理通知事件MediatR支持两种消息模式。Request/Response模式Notification模式在这篇文章中,我们将讨论Notification,然后创建一个实现了INotification接口的类,如下代码所示:}}为了能够处理LogEvent事件,需要创建一个实现了INotificationHandler接口的类,如下代码所示:Log(message);returnTask.FromResult(0);}privatevoidLog(stringmessage){//Writecodeheretologmessage(s)toatextfileDebug.WriteLine("Writecodeheretologmessage(s)toatextfile");}}publicclassDBNotificationHandler:INotificationHandler{publicTaskHandle(LogEventnotification,CancellationTokencancellationToken){publicTaskHandle(LogEventnotification,CancellationTokencancellationToken){strificationToken日志(消息);returnTask.FromResult(0);}privatevoidLog(stringmessage){//Writecodeheretologmessage(s)tothedatabaseDebug.WriteLine("Writecodeheretologmessage(s)tothedatabase");}}DependencyInjectionIMediator我刚刚为LogEvent创建了两个处理类,然后我可以通过依赖注入将它们注入到Controller中,如下代码所示:[ApiController][Route("[controller]")]publicclassWeatherForecastController:ControllerBase{privatereadonlyILogger_logger;privatereadonlyIMeditor_mediator;publicWeatherForecastController(IMeditormediator,ILoggerlogger){this._mediator=mediator;this._logger=logger;}}通过在publish中发布消息Action,如下代码所示:[HttpGet]publicIEnumerableGet(){_mediator.Publish(newLogEvent("HelloWorld"));}值得注意的是,上面的publish方法会在程序执行后被调用,然后触发DBNotificationHandler和FileNotificationHandler的Handle方法,如下图:中介模式是一种行为设计模式,can有效控制多个对象之间的交互,有效降低双方的依赖正好MediatR就是这样一个成品中介模型的实现。关于MediatR的request/response模型,我会在后面的文章中详细讲解翻译链接:https://www.infoworld.com/article/3393974/how-to-use-mediatr-in-aspnet-core。网页格式