【问题标题】:Resequencer for MediatR INotificationHandler - can't use IPipelineBehaviorMediatR INotificationHandler 的重测序器 - 无法使用 IPipelineBehavior
【发布时间】:2020-03-11 16:04:57
【问题描述】:

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

我可以看到文档提到:

管道行为只兼容 IRequestHandler<TRequest,TResponse> 不能与 INotificationHandler<TRequest>.

如果INotificationINotificationHandler 有等效的行为/转换管道,解决此问题的方法是什么?

或者是否会使用 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;
   }
}

只是想找出执行此操作的最佳位置,因为在 MediatRSimpleInjector 中似乎都可以执行此操作(至少使用 IRequests)。

【问题讨论】:

  • 好的,谢谢 Steven,如果您想将其作为答案弹出,这正是我正在寻找的答案,并将相应地标记。

标签: c# simple-injector mediatr


【解决方案1】:

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

【讨论】:

  • 感谢 Steven 也通过使用装饰器,我可以包装 INotification,这是我在这种情况下需要做的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 2021-09-02
  • 2021-06-18
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
相关资源
最近更新 更多