Reputation: 445
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
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
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.
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.
Upvotes: 0