Handler Ordering

Component: NServiceBus
NuGet Package NServiceBus (5.x)

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

How it is actually implemented

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

The inference here is that the remaining handlers (not specified in the order) are executed in a non-deterministic order.

With the configuration API

busConfiguration.LoadMessageHandlers(First<HandlerB>.Then<HandlerA>().AndThen<HandlerC>());

Specifying one to run first

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

Specifying multiple to run ordered

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

Last modified