Search code examples
c#asp.netdependency-injectionazureservicebusdispose

How to close and dispose Azure ServiceBusClient and ServiceBusSender singletons asynchronously when using dependency injection, e.g., in ASP.NET?


I want to use Azure Service Bus in .NET 7 applications, such as ASP.NET Core Web API pr Worker Service, which use dependency injection.

The official documentation recommends registering ServiceBusClient and ServiceBusSender as singletons:

The Service Bus objects that interact with the service, such as ServiceBusClient, ServiceBusSender, ServiceBusReceiver, and ServiceBusProcessor, should be registered for dependency injection as singletons (or instantiated once and shared).

It also says that dependencies will and must be disposed by the containter via the singleton's IDisposable.Dispose():

The container is responsible for cleanup of types it creates, and calls Dispose on IDisposable instances. Services resolved from the container should never be disposed by the developer. If a type or factory is registered as a singleton, the container disposes the singleton automatically.

Now, the problem with ServiceBusClient and ServiceBusSender is that both do NOT implement IDisposable but IAsyncDisposable instead. I couldn't find any documentation about whether the dependency injection container will also call (and await) IAsyncDisposable.DisposeAsync() automatically when shutting down the application.

Is that the case?

And if not, how else am I supposed to dispose the Azure Service Bus singletons when Services resolved from the container should never be disposed by the developer?


Solution

  • From the doc

    With regard to dependency injection, when registering services in an IServiceCollection, the service lifetime is managed implicitly on your behalf. The IServiceProvider and corresponding IHost orchestrate resource cleanup. Specifically, implementations of IDisposable and IAsyncDisposable are properly disposed at the end of their specified lifetime.