Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Aborting Pipeline execution

Component: NServiceBus
NuGet Package: NServiceBus (8.x)

From inside a Handler

From the context of a Handler, further handler execution can be aborted by calling the DoNotContinueDispatchingCurrentMessageToHandlers() method. This method instructs 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>
{
    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 is non-deterministic by default. 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 any nested behaviors.

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 injecting a behavior, see customizing the pipeline.


Last modified