Leow Kah Man
Leow Kah Man

Reputation: 445

Should Azure ServiceBusConnection be singleton?

In the old NuGet, it was good practice to retain the MessagingFactory instance.

Should we retain a single instance of ServiceBusConnection (from new Nuget) to be injected into multiple clients?

EDIT 2018-07-25 00:22:00 UTC+8:

Upvotes: 2

Views: 3059

Answers (2)

Sean Feldman
Sean Feldman

Reputation: 26012

Azure Service Bus .NET Standard client connections are not managed via QueueClient or any factory, like its predecessor used to. QueueClient is an abstraction on top of MessageSender and MessageReceiver that can take a ServiceBusConnection shared by multiple senders/receivers. You're free to choose either to share the same connection object or not.

var connection = new ServiceBusConnection(connectionString);
var queueClient1 = new QueueClient(connection, "queue1", ReceiveMode.PeekLock, RetryPolicy.Default);
var queueClient2 = new QueueClient(connection, "queue2", ReceiveMode.PeekLock, RetryPolicy.Default);
// Queue clients share the same connection
var message1 = new Message(Encoding.UTF8.GetBytes("Message1"));
var message2 = new Message(Encoding.UTF8.GetBytes("Message2"));

Based on the namespace tier you're using, you'll have to benchmark and see what works better for you. My findings showed that with Standard tier having multiple connections helps throughput, while with Premium tier it doesn't. This post hints at the reasons why it's so.

Upvotes: 3

Murray Foxcroft
Murray Foxcroft

Reputation: 13765

Not necessarily a singleton for all.

The right level of grain is the Messaging Factory. You may connect to a number of namespaces in your application, each will require their own MessageFactory and connection.

Alternatively you may have code that is not very async in it's nature and in this instance multiples connections (factories) make sense. For example you have two processes in your code, one that does a lot of work in a loop to send messages and another that receives, in this case two factories may be useful or you may refactor to make your code more async.

From the documentation.

It is recommended that you do not close messaging factories or queue, topic, and subscription clients after you send a message, and then re-create them when you send the next message. Closing a messaging factory deletes the connection to the Service Bus service.

In short, you should be re-using your message factories, which then maintain a connection to the service bus. Depending on how your code is written you may want to have multiple factories.

https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements#reusing-factories-and-clients

Upvotes: 0

Related Questions