Native message access

Component: Azure Service Bus Transport
NuGet Package NServiceBus.Transport.AzureServiceBus (2-pre)
Target NServiceBus Version: 8.x
This page targets a pre-release version and is subject to change prior to the final release.

Access to the native Azure Service Bus incoming message

It can sometimes be useful to access the native Service Bus incoming message from behaviors and handlers. When a message is received, the transport adds the native Service Bus Message to the message processing context. Use the code below to access the message details from a pipeline behavior:

class DoNotAttemptMessageProcessingIfMessageIsNotLocked : Behavior<ITransportReceiveContext>
{
    public override Task Invoke(ITransportReceiveContext context, Func<Task> next)
    {
        var lockedUntilUtc = context.Extensions.Get<Message>().SystemProperties.LockedUntilUtc;

        if (lockedUntilUtc <= DateTime.UtcNow)
        {
            return next();
        }

        context.AbortReceiveOperation();

        return Task.CompletedTask;
    }
}

The behavior above uses the native message's LockedUntilUtc system property to determine where the message lost its lock as a result of aggressive prefetching and slow processing. The message with the lost lock will not go through the recoverability process, skipping attempted processing that otherwise would be guaranteed to fail due to the message's lost lock.

Access to the native Azure Service Bus outgoing message

It can also be useful to access the native Service Bus outgoing message from behaviors and handlers for customizations.

// send a command
var sendOptions = new SendOptions();
sendOptions.CustomizeNativeMessage(m => m.Label = "custom-label");
await context.Send(new MyCommand(), sendOptions).ConfigureAwait(false);

// publish an event
var publishOptions = new PublishOptions();
publishOptions.CustomizeNativeMessage(m => m.Label = "custom-label");
await context.Publish(new MyEvent(), publishOptions).ConfigureAwait(false);

Last modified