4
votes

I would like my ASP.NET Core application to send messages to a Azure Service Bus.

In Microsoft's article Best Practices for performance improvements using Service Bus Messaging they argue that you should re-use instances of clients.

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.

So I take that as I should not instantiate a new instance of the client (TopicClient or QueueClient) inside my controller using the new keyword.

I guess that I should use dependency injection in ASP.NET Core.

Should I directly inject a TopicClient/QueueClient or should I create an own class that wraps an instance of the client and expose a SendAsync method?

When registering the service with dependency injector should I register it as a singleton?

1
Related. Confirmation that the clients are threadsafe. - StuartLC
@StuartLC What does this mean in the context of my question? - Fred
With each of the clients each you need to specify which queue or topic you intend communicating with, which can make it messy to inject the correct client instance into the correct injection site. So if you have multiple topics / queues, you can consider building your own wrapper which creates and caches the respective client instances. And the Azure clients are threadsafe, so there's no need to manage contention around them. - StuartLC

1 Answers

3
votes

We did it with a wrapper class that is then returning the TopicClient/QueueClient and registered it as a singleton and found no big issues with this approach.

We based our approach on this example provided by Microsoft eshopOnContainers.

The example code for this functionality is found in this file. They than register this class as singleton in Startup.cs in the services where they require ServiceBus.