Managing Azure Service Bus Connections

William Rees
4 min readJul 5, 2021

There are many tutorials that go over the features of Azure Service bus and demonstrate how to publish messages but in my experience I haven’t seen many posts that demonstrate the most optimal approach for applications with long lived processes such as a web application.

The typical example I see online looks something like this:

There’s absolutely nothing wrong with the sample code provided by Microsoft however it can be a little miss leading if you don’t consider the context in which this code was written.

The sample application that MS used was a console app which has a very short lifetime. The application will start, create a new client and sender, send a batch of messages and finally dispose the client & sender. In this context the code works without any issues however if the sample code was used in something like a web application you’ll likely start to encounter performance issues. This is because the official recommendation from MS is that both the client and senders should be singletons (docs can be found here: https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements?tabs=net-standard-sdk-2#reusing-factories-and-clients).

When using Azure Service Bus in an application that has a long lived process I like to implement the factory pattern to manage the lifetime of the service bus client and sender. You can also manage these instances using dependency injection however that can lead to other issues such as reuse of a closed client.

To demonstrate how this works I’ll do the following:

  1. Create an interface that will abstract sending messages to a bus
  2. Create an interface that will abstract the message bus factory
  3. Implement both interfaces for Azure Service Bus.
  4. Create a demo application that uses these interfaces.

Interface Definitions

--

--

William Rees

Software engineer with 10+ years of experience. I primarily work on the Microsoft and .NET ecosystem and have extensive experience with Microsoft Azure