开源地址:https://github.com/jbogard/MediatR
依赖注入:https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection
1、NuGet添加引用包 MediatR.Extensions.Microsoft.DependencyInjection
2、依赖注入相关服务
services.AddMediatR(System.Reflection.Assembly.GetExecutingAssembly()); //把自定义的消息类,处理消息类注入到服务中
3、MediatR会分派两种消息
a.单播:请求/响应消息,分派给单个处理程序
b.多播:通知消息,分派给多个处理程序
4、单播的消息
a.定义消息类型,继承MediatR.IRequest接口的消息类
IRequest<T>:有返回值单播消息
IRequest 无返回值单播消息
public class Ping : IRequest<string>
{
//可以自定义任意的字段
public string Title { get; set; }
public string Content { get; set; }
}
b.创建处理消息的类,继承IRequestHandler<Ping, string>: Ping消息类,string消息类接受处理结果的类型
public class PingHandler : IRequestHandler<Ping, string>
{
public Task<string> Handle(Ping request, CancellationToken cancellationToken)
{
Console.WriteLine("PingHandler Doing..." + request.Title);
return Task.FromResult("ok");
}
}
c.使用中介者发送单播消息
IMediator mediator = context.RequestServices.GetRequiredService<IMediator>(); //可以使用依赖注入的方式获得mediator
Ping ping = new Ping() { Title = "TestTitle" };
string result = await mediator.Send(ping);
await context.Response.WriteAsync(result);
5.多播消息
a.定义多播消息类,需要继承INotification
public class NotyPing : INotification
{
public string Message { get; set; }
}
b.定义一个或多个处理消息类
public class Noty1Handler : INotificationHandler<NotyPing>
{
public Task Handle(NotyPing notification, CancellationToken cancellationToken)
{
Console.WriteLine("Noty1Handler Doing..."+notification.Message);
return Task.CompletedTask;
}
}
public class Noty2Handler : INotificationHandler<NotyPing>
{
public Task Handle(NotyPing notification, CancellationToken cancellationToken)
{
Console.WriteLine("Noty2Handler Doing..." + notification.Message);
return Task.CompletedTask;
}
}
c.发布消息
IMediator mediator = context.RequestServices.GetRequiredService<IMediator>();
NotyPing notyPing = new NotyPing { Message = "Test Noty" };
await mediator.Publish(notyPing);
d.多路广播发布策略问题
Publish 方法的默认实现:同步循环每个处理程序,一个失败不影响后边的处理程序,这样可以确保每个处理程序都依次运行,而且按照顺序运行。
根据发布通知的不同需求,您可能需要不同的策略来处理通知,也许您想并行发布所有通知,或者使用您自己的异常处理逻辑包装每个通知处理程序。
在 MediatR.Examples.PublishStrategies 中可以找到一些示例实现, 其实就是使用 PublishStrategy 枚举设置不同的策略,参考以下链接。
6.类型协变(单播处理器和多播处理器)
例如:您可以实现 INotificationHandler <INotification> 来处理所有通知
本文介绍了如何利用MediatR库在.NET应用中实现依赖注入和消息处理。首先,通过NuGet添加MediatR.Extensions.Microsoft.DependencyInjection引用,然后配置依赖注入服务。MediatR支持单播和多播消息,单播包括有返回值和无返回值的消息类型,多播则涉及INotification接口。文章详细展示了定义消息类、处理程序以及如何发送和发布消息的步骤。此外,还提及了发布策略的自定义可能性以及类型协变的概念。

被折叠的 条评论
为什么被折叠?



