So, I've registered a named client with the services collection in my Startup.cs:
services.AddHttpClient(someServiceName, client => client.BaseAddress = baseAddress);
and now can inject an IHttpClientFactory
from my service provider.
Using this IHttpClientFactory
, I conjure up a client instance:
var client = httpClientFactory.CreateClient(someServiceName)
Once upon a time, it was necessary to be very careful about the disposing of HttpClient
instances, as it was rarely the right thing to do.
However, now we have HttpClientFactory
, does this matter any more? Should/Can this client
be disposed without worry? e.g.
using (var httpClient = httpClientFactory.CreateClient(someServiceName)) using (var response = await httpClient.PostAsync(somePath, someData)) { var content = await response.Content.ReadAsAsync<SomeResponse>(); //... }
The HttpClient instances injected by DI, can be disposed of safely, because the associated HttpMessageHandler is managed by the factory. As a matter of fact, injected HttpClient instances are Scoped from a DI perspective.
When you use the same instance of HttpClient for multiple requests (sequential and concurrent) to the same URL, it'll reuse connections. Requests that get to reuse a connection are 5.5-8.5x faster than requests that have to open a new connection.
It has a method CreateClient which returns the HttpClient Object. But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood.
The safest, general advice would be to always dispose of the HttpResponseMessage once you have finished with using it. This does lead to a little more code noise but ensures that regardless of the internals and any future changes, your code will free/clean up unused resources such as connections as quickly as possible.
No. You should not dispose of your client. To be more general, you should not dispose of anything retrieved via a DI container, which in ASP.NET Core is by default the service collection. The lifetime is managed by the DI container, so if you dispose of the client, but it's later injected into something, you'll get an ObjectDisposedException
. Let the container handle disposal.
This is actually a common confusion with IDisposable
classes. You should personally only implement IDisposable
if your class itself owns dependencies. If all its dependencies are injected, you should not implement IDisposable
, since it doesn't own anything that needs disposal. Likewise, you should not dispose of anything injected into your class, as it doesn't own those dependencies. Only dispose of things you specifically new up. If you don't see the keyword new
, you probably shouldn't be disposing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With