【.NET 生态】MediatR

MediatR 是一个用来实现中介者模式的开源工具,用来将进程内消息的发送者和消费者进行解耦。可以方便的实现事件总线模式。

应用场景

  1. 实现 EventBus
  2. 实现 CQRS

核心类

  • IMediator
  • IRequest
  • IRequestHandler<in TRequest, TResponse>
  • INotification
  • INotificationHandler
  • IPipelineBehavior<TRequest, TResponse>:支持在请求处理前和请求处理后添加额外行为,比如日志记录、认证授权、数据校验等
  • IRequestPreProcessor

最佳实践

将 Mediator 实例作为控制器的属性

public abstract class BaseController : ControllerBase
{
    private IMediator _mediator = null!;

    protected IMediator Mediator
        => _mediator
        ??= HttpContext.RequestServices.GetRequiredService<IMediator>();
}
posted @ 2022-06-02 13:41  weidadong  阅读(880)  评论(0)    收藏  举报