DEV Community

Discussion on: C# Tip: use IHttpClientFactory to generate HttpClient instances

Collapse
 
fluffynuts profile image
Davyd McColl

Incorrect - unless you want to set default headers or connection handlers (docs.microsoft.com/en-us/aspnet/co...), HttpClient is thread-safe (docs.microsoft.com/en-us/dotnet/ap...) and does not block on requests.

In fact, we use this static pattern a lot in a highly-concurrent environment, and have been doing so for years.

TL;DR: if you're willing to specify all requests fully (ie, full url, required headers (if any)) then a static HttpClient is just fine. If you aren't doing tricks with headers, then your only requirement here is to fully qualify request urls, which isn't just a big requirement.

Here's a demo to prove it: github.com/fluffynuts/ConcurrentHt... - if you run that, I see 10 sequential requests to google.com taking around 5 seconds, and 10 parallel requests taking around 1 second.

Thread Thread
 
bellonedavide profile image
Davide Bellone

Ah, I see. Interesting.

Silly question: if it works, why did the .NET team created the HttpClientFactory? Only for customizing single HTTP clients with stuff like BaseUrl and headers?

Thread Thread
 
fluffynuts profile image
Davyd McColl

docs.microsoft.com/en-us/dotnet/ar...

Mostly because most people often use HttpClient incorrectly - disposing and recreating clients, which is expensive. Hiding this behind a factory means you don't see that you're getting the same instance, and you have an injectable service to provide this instance. Also, you can create clients with common config (headers, baseurl, etc) and just rely on getting the "correct one" when you ask for it by name or as an injectable constructor parameter for a service of your own. The factory should ensure better life-cycles for your consumed HttpClient instances because they can (as demonstrated) be re-used and used in parallel, without issue.

Thread Thread
 
fluffynuts profile image
Davyd McColl

I must be clear that there's nothing wrong with using IHttpClientFactory - just that it's not the only way to work with HttpClient instances performantly.