MediatR中介类的应用

简介

MediatR是开源的,.net中的中介模式实现,一种进程内消息传递机制。支持同步或异步形式进行请求/响应,命令,查询,通知和事件的消息传递,并通过c#泛型支持消息的智能调度。

中介模式的优点:减少类间的依赖,原一对多的依赖变成了一对一依赖,降低了类间的耦合
中介模式的缺点:逻辑变得复杂

MediatR中的核心对象

  1. IRequest Vs IRequestHandler
  2. INotification Vs INoticifaitonHandler
  3. IMediator Vs Mediator
  4. Unit
  5. IPipelineBehavior

MediatR中处理一对一消息时,使用IRequest、IRequestHandler
MediatR中处理一对多消息时,使用INotification、INoticifaitonHandler
IRequestHandler 可以返回结果
INoticifaitonHandler 无返回结果

使用IMediatoR

NuGet中搜索MediatR,并安装,如果是asp.net core项目,安装MediatR.Extensions.Microsoft.DependencyInject

1.asp.net core 项目 Startup.cs中注册服务

public void ConfigureServices(IServiceCollection services)
{
            services.AddRazorPages(); 
            services.AddMediatR(typeof(Program)); //注册mediatr
}

2.在构造方法注入IMediator

IMediator mediator;
public HomeController(IMediator _mediator)
{
  mediator=_mediator;
}

public async Task test()
{
  int result= await mediator.Send(new Request());//消息请求
  await mediator.Publish(new Notification());  //消息订阅
}

实例代码

IRequest Vs IRequestHandler

 public static class Data
    {
        public static List<int> Value { get; set; } = new List<int>();
    }
    class Request:IRequest<int>
    {

    }
    class RequestHandler2 : IRequestHandler<Request, int>
    {
        public async Task<int> Handle(Request request, CancellationToken cancellationToken)
        {
            Data.Value.Add(2);
            return 2;
        }
    }
class RequestHandler1 : IRequestHandler<Request, int>
    {
        public async Task<int> Handle(Request request, CancellationToken cancellationToken)
        {
            Data.Value.Add(1);
            return 1;
        }
    }

INotification Vs INoticifaitonHandler

 class Notification : INotification
    {
        
    }
    class NotificationHandler2 : INotificationHandler<Notification>
    {
        public async Task Handle(Notification notification, CancellationToken cancellationToken)
        {
            Data.Value .Add(2);
        }
    }
    class NotificationHandler1 : INotificationHandler<Notification>
    {
        public async  Task Handle(Notification notification, CancellationToken cancellationToken)
        {
            Data.Value.Add( 1);
        }
    }
    class NotificationHandler3 : INotificationHandler<Notification>
    {
        public async Task Handle(Notification notification, CancellationToken cancellationToken)
        {
            Data.Value.Add(3);
        }
    }

注意事项

如果IRequest对应的IRequestHandler定义了多个,那么只有第一个IRequestHandler有效
INotification对应的多个INotificationHandler将按先后顺序,依次执行完。
IRequestHandler 有返回结果
INoticifaitonHandler 无返回结果

参考资料

MediatR in github
RsCode
应用MediatR的web应用实例

posted @ 2021-09-13 10:42  奎宇工作室  阅读(154)  评论(0)    收藏  举报