Handler Ordering

Component: NServiceBus
NuGet Package NServiceBus (4.x)
Standard support for version 4.x of NServiceBus has expired. For more information see our Support Policy.

Multiple classes may implement IHandleMessages<T> for the same message. In this scenario, all handlers will execute in the same transaction scope. These handlers can be invoked in any order but the order of execution can be specified in code

Overview of the implementation

  1. Find the list of possible handlers for a message.
  2. If an order has been specified for any of those handlers, move them to the start of the list.
  3. Execute the handlers.

The remaining handlers (i.e. ones not specified in the ordering) are executed in a non-deterministic order.

With the configuration API

var configUnicastBus = configure.UnicastBus();
configUnicastBus.LoadMessageHandlers(First<HandlerB>.Then<HandlerA>().AndThen<HandlerC>());

Specifying one handler to run first

public class MySpecifyingFirst :
    ISpecifyMessageHandlerOrdering
{
    public void SpecifyOrder(Order order)
    {
        order.SpecifyFirst<HandlerB>();
    }
}

Specifying multiple handlers to run in order

public class MySpecifyingOrder :
    ISpecifyMessageHandlerOrdering
{
    public void SpecifyOrder(Order order)
    {
        order.Specify(typeof(HandlerB),typeof(HandlerA),typeof(HandlerC));
    }
}

Last modified