Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resequencer for MediatR INotificationHandler - can't use IPipelineBehavior

I have seen MediatR IPipelineBehavior<TRequest, TResponse> and looking to use a resequencer for event bus notifications to be put in order. The aspect orientated angle is very interesting/useful to split up functionality into separate handlers.

I can see the docs mention:

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

What would be the way around this is there an equivalent behaviors/transformation pipeline for INotification and INotificationHandler?

Or would one use a DI container such as my favorite SimpleInjector and register decorators to wrap specific event handlers where i want re-sequencing to take place by wrapping specific notification handlers?

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;
   }
}

Just trying to work out the best place to do this, as seem to be able to do this (with IRequests at least) both in MediatR and SimpleInjector.

like image 507
morleyc Avatar asked Oct 13 '25 01:10

morleyc


1 Answers

Personally, I would certainly ditch those pipeline behaviors and replace them with decorators. Decorators make a much simpler model to implement cross-cutting concerns. Older versions of MediatR actually used decorators instead of these pipeline behavior. AFAIK, the only reason newer MediatR versions don't use decorators is because it tries to make a model that works on all containers, even on those that have poor support for decorators (such as MS.DI, Unity, etc.).

like image 140
Steven Avatar answered Oct 14 '25 17:10

Steven