c# - MediatR INotificationHandler 的重新排序器 - 无法使用 IPipelineBehavior

标签 c# simple-injector mediatr

我看过 MediatR IPipelineBehavior<TRequest, TResponse>并希望使用重新排序器来整理事件总线通知。面向方面的角度对于将功能拆分为单独的处理程序非常有趣/有用。

我可以看到文档提到:

pipeline behaviors are only compatible with IRequestHandler<TRequest,TResponse> and can't be used with INotificationHandler<TRequest>.

如果 INotification 有一个等效的行为/转换管道,那么解决这个问题的方法是什么?和 INotificationHandler

或者会使用 DI 容器,例如我最喜欢的 SimpleInjector并注册装饰器以包装特定的事件处理程序,我希望通过包装特定的通知处理程序来重新排序?

class ResequencerEventHandler<T> : INotificationHandler<T> where T : INotification, ISequencedMessage
{
   readonly IResequencer _resequencer;
   readonly INotificationHandler<T> _handler;

   public ResequencerEventHandler(INotificationHandler<T> handler, IResequencer resequencer)
   {
      _resequencer = resequencer;
      _handler = handler;
   }

   public Task Handle(T notification)
   {
      _resequencer.Add(notification);

      while(_resequencer.CanDequeue)
      {
          var packet = _resequencer.Dequeue();
          _handler(packet);
      }

      return Task.CompletedTask;
   }
}

只是想找出执行此操作的最佳位置,因为似乎能够在 MediatR 中执行此操作(至少使用 IRequests)和 SimpleInjector .

最佳答案

就个人而言,我肯定会放弃那些管道行为并用装饰器替换它们。装饰器创建了一个更简单的模型来实现横切关注点。旧版本的 MediatR 实际上使用了装饰器而不是这些管道行为。据我所知,较新的 MediatR 版本不使用装饰器的唯一原因是因为它试图制作一个适用于所有容器的模型,即使是那些对装饰器支持不佳的容器(例如 MS.DI、Unity 等)。

关于c# - MediatR INotificationHandler 的重新排序器 - 无法使用 IPipelineBehavior,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60640124/

相关文章:

c# - Mediatr 无法解析 ASP.Net Core 中的 UserManager

c# - MediatR 共享 TableBatchOperation 以在不同的处理程序中进行事务保存

c# - 简单注入(inject)器 - 将 url 值注入(inject)到服务构造函数中

c# - 抽象不能代替部分吗?

c# - 从 ViewModel 控制 TextBox 的滚动位置?

c# - 用于 C# 的 minpack fortran .dll

c# - 在 Web API 和 OWIN 中使用简单注入(inject)器

c# - 在 Simple Injector v3.0.3 中使用 ResolveUnregisteredType 会导致 Torn Lifestyle 警告

c# - 使用 MediatR 执行 API 方法时出现错误

c# - 为什么要在 WinForm 对话框上使用 InitializeLifetimeService?