DEV Community

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

 
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.