Skip to content

Azure Service Bus

Robin Rodricks edited this page Jan 18, 2023 · 6 revisions

In order to use Microsoft Azure Service Bus you need to reference NuGet first. The provider wraps around the standard Microsoft Service Bus SDK.

This provider supports both topics and queues, for publishing and receiving. To construct a publisher use the following:

IMessagePublisher queuePublisher = StorageFactory.Messages.AzureServiceBusQueuePublisher(
                       connectionString,
                       queueName);

IMessagePublisher topicPublisher = StorageFactory.Messages.AzureServiceBusTopicPublisher(
                       connectionString,
                       topicName);

To construct a receiver, use the following:

IMessageReceiver queueReceiver = StorageFactory.Messages.AzureServiceBusQueueReceiver(
                       connectionString,
                       queueName,
                       peekLock);

IMessageReceiver topicReceiver = StorageFactory.Messages.AzureServiceBusTopicReceiver(
                       connectionString,
                       topicName,
                       subscriptionName,
                       peekLock);

peekLock is a flag indicating how to receive the message, is optional, and is true by default.

You also have an options to pass your own MessageHandlerOptions to customise service bus behavior. For instance, if you need to define an exception handler that doesn't ignore errors (default behavior) and set for instance concurrency to more than 1 message (default) you could write the following:

var options = new MessageHandlerOptions(tExceptionReceiverHandler)
{
  AutoComplete = false,
  MaxAutoRenewDuration = TimeSpan.FromMinutes(1),
  MaxConcurrentCalls = 5 //instead of 1
};

private async Task ExceptionReceiverHandler(ExceptionReceivedEventArgs args)
{
    // your exception handling code
}

IMessageReceiver topicReceiver = StorageFactory.Messages.AzureServiceBusTopicReceiver(
                       connectionString,
                       topicName,
                       subscriptionName,
                       peekLock,
                       options);

Note that exception handler in Service Bus is for informational purposes only, it doesn't actually handle exceptions, and in case of errors the SDK retries them automatically.

Clone this wiki locally