Aborting Pipeline execution

Component: NServiceBus
NuGet NServiceBus (5.x)

From inside a Handler

From the context of a Handler further Handler execution can be aborted by calling the DoNotContinueDispatchingCurrentMessageToHandlers() method. This method instruct the bus not to pass the current message on to subsequent handlers in the pipeline. This is often used by authentication and authorization handlers when those checks fail.

class Handler :
    IHandleMessages<MyMessage>
{
    IBus bus;

    public Handler(IBus bus)
    {
        this.bus = bus;
    }

    public void Handle(MyMessage message)
    {
        // may want to log a reason here
        bus.DoNotContinueDispatchingCurrentMessageToHandlers();
    }
}

Aborting the pipeline does not fail the message processing. The message that was processed will be marked as successfully completed.

Handler execution order by default is non-deterministic. To configure the ordering see Handler Ordering.

Via a pipeline Behavior

The pipeline can also be aborted by injecting a custom Behavior that, with some custom logic, optionally decides to abort Behaviors nested inside it.

public class Behavior :
    IBehavior<IncomingContext>
{
    public void Invoke(IncomingContext context, Action next)
    {
        if (ShouldPipelineContinue(context))
        {
            next();
        }
        // since next is not invoke all downstream behaviors will be skipped
    }

    bool ShouldPipelineContinue(IncomingContext context)
    {
        // the custom logic to determine if the pipeline should continue
        return true;
    }
}

For more information about creating and where to inject a behavior see customizing the pipeline.


Last modified