Will dependency injection dispose the following registration?

Viewed 48

By looking into the MS docs for dependency injection it is clear that DI will dispose of the object that is injected by DI according to their lifetime. I'm little confused/not sure what will happen in the following case with BlobContainerClient object. Will it get disposed of with EventProcessorClient.

services.TryAddScoped<EventProcessorClient>(p =>
{
    var storageClient = new BlobContainerClient("connectionString", "containerName");
    var connectionParam = p.GetRequiredService<IOptions<EventHubSettings>>();
    return new EventProcessorClient(storageClient, connectionParam.Value.SomeValue,
        connectionParam.Value.SomeValue);
});
1 Answers

Referring to the same docs

The container calls Dispose for the IDisposable types it creates. 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.

Reference

Looking at the code example neither the EventProcessorClient class or the BlobContainerClient class implement the IDisposable interface. This means the dependencies will not be "explicitly" disposed (through an IDisposable.Dispose() method call).

What will happen is the objects storageClient, connectionParam and the EventProcessorClient will be marked for clean up by the Garbage Collector.

Now given this is a Scoped service lifetime these events will happen when the scope is disposed. Either through (with a web application) when the request ends, or the scope is explicitly disposed (with a using statement).

To add (from the example) if the BlobContainerClient implemented the IDisposable interface it would not be automatically disposed when the scope ends. This is because the object was constructed manually (not via the lifetime scope object) so therefore would not be tracked by the scope.

Related