0

I am using the package Microsoft.Azure.ServiceBus. Since I should reuse the TopicClient to get the best use out of AMQP/SBMP, I would be creating it once inside one of my singleton services. However, TopicClient is not IDisposable, It only exposes the method CloseAsync.

What should I do? Do I even need to call this method in my context? The documentation is not really clear about it.

https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.servicebus.topicclient?view=azure-dotnet#methods

Closes the Client. Closes the connections opened by it.

This is my current draft:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(sp => new MyService());
...


public sealed class MyService: IDisposable
        public void Dispose()
        {
            _TopicClient.CloseAsync().GetAwaiter().GetResult();
        }

PS: I am only putting messages into the topic, nothing else.

Alex AIT
  • 17,361
  • 3
  • 36
  • 73

1 Answers1

2

Basically the rule is like this:

If you open it, you should close it. However:

  • if IDisposable is implemented this is often done implicit
  • some IDisposables work better if kept alive (HttpClient)
  • opening and closing cost a significant amount of time
  • this is with respect to the lifetime scope.

So,

Since you have a singleton (application life time scope), you should keep it open unless you hit issues.

Besides that, in general, bus connections are typically always left open.

It would be nice to close it on application exit, but even this isn't mandantory.

side note: the topic client in your Singleton might not be thread safe. I would double check that.


So when would you close this bus connection?

There will be scenarios where you might want a explicit call to close.

E.g.: - your connection is unstable (satelite or long wave radio). In this case, if you send every now and then you might want to open, send and close. - your total amount of connections is reaching maximum. - if you send something at a very low interval (like once an hour, than it would just save some resources) - high amount of concurrent tasks (if the client isnt thread safe)

There are many more, but its always depending on the use case. Its a good thing to keep in mind, that if you run into problems, it might be due to using only one connection.

Stefan
  • 17,448
  • 11
  • 60
  • 79