What are the Best Practices with using HttpClient & HttpClientHandler for multiple endpoints?

2.2k Views Asked by At

Using HttpClient is not as straight forward as I would've hoped. Despite it being an IDisposable type it is not best practice to wrap it in a using statement and it's even ideal to make it a singleton. However, what about when you pass in a HttpClientHandler to the constructor of the HttpClient like:

using (var client = new HttpClient(singletonHttpClientHandler, false);

I've seen code like above where the HttpClient is deliberately wrapped in a using statement but the HttpClientHandler is a singleton. The docs indicate the client handler is disposed of unless the second param indicates false as is done above:

enter image description here

See https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#constructors

Part of the problem with using HttpClient is several things like a timeout must be shared with all instances of that HttpClient, so for this reason it would be nice to create separate instances of HttpClient that use the same connection pool presumably provided by the HttpClientHandler (assuming that is how this works). My concern is that I don't want HttpClient to create a connection pool that will then be disposed of each time. There's multiple posts on how this is really bad for performance. I can't seem to find any good documentation on effectively using HttpClient together with HttpClientHandlers.

So... My question is basically:

When using an HttpClient & HttpClientHandler together, is it best to make the HttpClientHandler a singleton and then instantiate as many new HttpClients in using blocks each time? -- This again only makes sense if the connection pool is managed by the HttpClientHandler, which I think is the case.

0

There are 0 best solutions below