Creating and disposing KeyVaultClient in .NET

Viewed 1457

Little confused what are the best practices for creating and disposing KeyVaultClient objects.

I am currently instantiating KeyVaultClient in the following way:

var azureServiceTokenProvider = new AzureServiceTokenProvider();

_keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback), httpClient);

I am currently creating httpClient using an injected IHttpClientFactory. What does KeyVaultClient actually do if I don't supply the HttpClient? I assume it is creating it's own instance of HttpClient, but how does it manage that instance?

KeyVaultClient implements IDisposable. Obviously under the hood KeyVaultClient is using a HttpClient instance and I have heard in many places that its not a good idea to dispose of HttpClient after each usage (say a single GET call). Does this mean I should be avoiding the disposing of KeyVaultClient as well as it will dispose my provided httpClient instance?

Any clarification on this would be great.

1 Answers

If the HttpClient is created with the default constructor it takes care of holding all resources and also disposes them on its own dispose. When using the HttpClient from the factory it uses a different constructor providing its own HttpMessageHandler (that's the one that will hold the socket). In this specific case the implementation will be taken from a pool in the factory (that still holds a reference to it) and calling dispose on the HttpClient will call dispose on the HttpMessageHandler, but that won't close the resources, but putting it back into the pool as available for the next client. Thous avoiding an overflow of open sockets.

So by providing an client from the factory and injecting this into the KeyVaultClient that only has a scoped lifetime will taking care of managing the sockets and is IMHO the best way of usage. Instead, registering the KeyVaultClient as singleton will lead to problems that the HttpClientFactory helps to avoid.

Related