Aborting Pipeline execution

Component: NServiceBus | Nuget: NServiceBus (Version: 6.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.

Edit
class Handler :
    IHandleMessages<MyMessage>
{
    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        context.DoNotContinueDispatchingCurrentMessageToHandlers();
        return Task.CompletedTask;
    }
}

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.

Edit
public class Behavior :
    Behavior<IIncomingLogicalMessageContext>
{
    public override Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next)
    {
        if (ShouldPipelineContinue(context))
        {
            return next();
        }
        // since next is not invoke all downstream behaviors will be skipped
        return Task.CompletedTask;
    }

    bool ShouldPipelineContinue(IIncomingLogicalMessageContext 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