MediatR是一个开源项目,是Mediator设计模式的一种实现。 介体设计模式控制着一组对象的通信方式,并有助于减少必须管理的这些对象之间的依赖关系数。 在中介程序设计模式中,对象之间不直接进行通信,而是通过中介程序进行通信。 本文讨论了如何在ASP.Net Core应用程序中使用MediatR。
在Visual Studio中创建一个ASP.Net Core项目
首先,让我们在Visual Studio中创建一个ASP.Net Core项目。 假设系统中已安装Visual Studio 2017或Visual Studio 2019,请按照以下概述的步骤在Visual Studio中创建新的ASP.Net Core项目。
- 启动Visual Studio IDE。
- 点击“创建新项目”。
- 在“创建新项目”窗口中,从显示的模板列表中选择“ ASP.Net Core Web应用程序”。
- 点击下一步。
- 在接下来显示的“配置新项目”窗口中,指定新项目的名称和位置。
- 单击创建。
- 接下来显示一个新窗口“创建新的ASP.Net Core Web应用程序”。
- 选择.Net Core作为运行时,并从顶部的下拉列表中选择ASP.Net Core 2.2(或更高版本)。
- 选择“ Web应用程序”作为项目模板。
- 确保未选中“启用Docker支持”和“配置HTTPS”复选框,因为我们此处将不再使用这些功能。
- 确保将身份验证设置为“无身份验证”,因为我们也不会使用身份验证。
- 单击创建。
这将在Visual Studio中创建一个新的ASP.Net Core项目。 我们将在本文的后续部分中使用此项目,以通过MediatR实现我们的中介器模式。
在ASP.Net Core项目中安装MediatR
在ASP.Net Core中使用MediatR非常简单。 在撰写本文时,MediatR的当前版本是7.0.0。 假设您已经在Visual Studio中创建了一个ASP.Net Core项目,下一步是安装以下NuGet包。
- 中介
- MediatR.Extensions.Microsoft.DependencyInjection
为此,您可以使用NuGet软件包管理器或NuGet软件包管理器控制台。
在ASP.Net Core中配置MediatR
一旦在您的项目中成功安装了前面部分提到的两个软件包,下一步就是在Startup类中配置MediatR。 为此,您应该在ConfigureServices方法中编写以下代码。 请注意,ConfigureServices方法用于在运行时将服务添加到容器。
public void ConfigureServices(IServiceCollection services)
{
services.AddMediatR(typeof(Startup));
services.AddMvc().SetCompatibilityVersion
(CompatibilityVersion.Version_2_2);
}
使用MediatR处理ASP.Net Core中的通知事件
MediatR支持两种类型的消息:请求/响应和通知。 在此示例中,我们将研究如何使用MediatR处理通知事件。
现在,创建一个扩展MediatR的INotification接口的类,如下所示。
public class LogEvent : INotification
{
public string message;
public LogEvent(string message)
{
this.message = message;
}
}
要为此事件创建处理程序,您应该创建实现INotificationHandler接口的类,如下所示。
public class FileNotificationHandler : INotificationHandler<LogEvent>
{
public Task Handle(LogEvent notification,
CancellationToken cancellationToken)
{
string message = notification.message;
Log(message);
return Task.FromResult(0);
}
private void Log(string message)
{
//Write code here to log message(s) to a text file
}
}
public class DBNotificationHandler : INotificationHandler<LogEvent>
{
public Task Handle(LogEvent notification,
CancellationToken cancellationToken)
{
string message = notification.message;
Log(message);
return Task.FromResult(0);
}
private void Log(string message)
{
//Write code here to log message(s) to the database
}
}
使用依赖项注入在ASP.Net Core中注入IMediator实例
到目前为止,一切都很好。 我们为先前创建的LogEvent有两个处理程序。 接下来,我们将利用依赖注入。 以下代码段显示了如何使用构造函数注入来注入IMediator实例。
public class ValuesController : ControllerBase
{
private readonly IMediator _mediator;
public ValuesController(IMediator mediator)
{
this._mediator = mediator;
}
//Write your controller methods here
}
最后,您可以使用以下代码从控制器方法发布事件。
_mediator.Publish(new LogEvent("Hello World"));
调用Publish方法将调用DBNotificationHandler和FileNotificationHandler类的Handle方法。
中介者设计模式是一种行为模式,它定义一个对象,该对象封装了一组对象之间的交互方式。 MediatR是介体设计模式的实现,可帮助您解耦命令/查询/事件处理代码。 我将在以后的文章中演示如何使用MediatR处理请求/响应消息。
From: https://www.infoworld.com/article/3393974/how-to-use-mediatr-in-aspnet-core.html