Handler Ordering

Component: NServiceBus
NuGet Package NServiceBus (7.x)

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

endpointConfiguration.ExecuteTheseHandlersFirst(
    typeof(HandlerB),
    typeof(HandlerA),
    typeof(HandlerC));

Specifying one handler to run first

endpointConfiguration.ExecuteTheseHandlersFirst(typeof(HandlerB));

Specifying multiple handlers to run in order

endpointConfiguration.ExecuteTheseHandlersFirst(
    typeof(HandlerB),
    typeof(HandlerA),
    typeof(HandlerC));

Last modified