一、什么是MediatR
MediatR是一个在.NET应用程序中实现"中介者模式"的开源库。中介者模式是一种行为设计模式,它允许对象之间通过一个中介者对象进行交互,而不是直接相互依赖和交互。MediatR通过将请求和处理程序解耦,使应用程序的不同组件之间的通信更加简单和灵活。通过将请求封装在一个对象中,然后将该对象传递给中介者,中介者将选择正确的处理程序来处理该请求。MediatR还提供了一些功能,如管道处理程序(Pipeline Behaviors)、日志记录、异常处理等,以增强中介者模式的功能和灵活性。
二、消息传递的方式
1、一对一
一对一消息传递是指一个消息只能被一个处理程序处理。当一个消息被发送到Mediator时,Mediator会将该消息发送给与之关联的处理程序。
2、一对多
一对多消息传递是指一个消息可以被多个处理程序处理。当一个消息被发送到Mediator时,Mediator会将该消息发送给与之关联的所有处理程序。
三、MediatR的实现
在Program.cs文件中注册服务
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
1、一对一
消息只能被一个处理程序处理,如有多个,只会处理第一个消息发布者。
第一步
创建一个实体类继承IRequest<T>接口,T是后面返回值的类型。
public record GetNotification : IRequest<int>
{
public string Name { get; set; }
public int Age { get; set; }
public GetNotification(string name, int age)
{
Name = name;
Age = age;
}
}
第二步
创建一个处理器继承IRequestHandler<T, T>接口,第二个T为返回值类型。
public class GetNotifiHander : IRequestHandler<GetNotification, int>
{
public async Task<string> Handle(GetNotification request, CancellationToken cancellationToken)
{
Console.WriteLine("你好" + request.Name + "你的年龄" + request.Age);
return 666;
}
}
第三步
创建一个控制器,注入IMediator服务。
private IMediator mediator;
public PostController(IMediator mediator)
{
this.mediator = mediator;
}
[HttpPost]
public async void Bdd(string name, int age)
{
int returnint = await mediator.Send(new GetNotification(name, age));
Console.WriteLine(returnint);
}
2、一对多
消息可以被多个处理程序处理。
第一步
创建一个实体类,继承INotification接口。
public record PostNotification() : INotification
{
public string Body { get; set; }
public string Title { get; set; }
public PostNotification(string body, string title) : this()
{
Body = body; Title = title;
}
}
第二步
创建一个或多个处理器,并且继承: NotificationHandler<T>接口。
public class PostNotifHander : NotificationHandler<PostNotification>
{
protected override void Handle(PostNotification notification)
{
Console.WriteLine("123" + notification.Body);
}
}
public class PostNotifHanders : NotificationHandler<PostNotification>
{
protected override void Handle(PostNotification notification)
{
Console.WriteLine("我也被实现了" + notification.Body);
}
}
第三步
创建一个控制器,注入IMediator服务。
private IMediator mediator;
public PostController(IMediator mediator)
{
this.mediator = mediator;
}
[HttpPost]
public voidAdd(string body, string title)
{
mediator.Publish(new PostNotification(body, title));
}