There is a problem with HttpClient 80% of developers
- Don't know about You call external APIs in almost every project.
- Many devs just use one Singleton HttpClient for all HTTP calls and they are completely wrong.
- Singleton HttpClient doesn't resolve ๐๐ก๐ฆ ๐ฎ๐ป๐ฑ ๐ป๐ฒ๐๐๐ผ๐ฟ๐ธ ๐ฐ๐ต๐ฎ๐ป๐ด๐ฒ๐. I encountered an issue where an internet provider network failure caused my application to stop sending HTTP requests until it was restarted.
Maybe we can just create an HttpClient for each call with a using statement?
- This is the second common mistake. Sooner or later, you can get a ๐ฃ๐ผ๐ฟ๐ ๐๐ ๐ต๐ฎ๐๐๐๐ถ๐ผ๐ป problem. As disposed, HttpClient doesn't immediately free up the used Socket under the hood.
Let's explore the 3 ways to use HttpClient correctly:
- HttpClientFactory with Named Client
- HttpClientFactory with Typed Client
- HttpClientFactory with Refit library
- HttpClientFactory contains a pool of HttpClients and caches them. Each time you need an HttpClient, you resolve it from the Factory.
๐ฃ๐ฟ๐ผ๐:
- Solves DNS refresh & socket exhaustion
- Central place to configure default policies
- Lightweight, part of Microsoft.Extensions.Http
๐๐ผ๐ป๐:
- You need to write boilerplate code to resolve HttpClient before sending each request
- You still pass raw URLs & strings around
- ๐ง๐๐ฝ๐ฒ๐ฑ ๐๐๐๐ฝ๐๐น๐ถ๐ฒ๐ป๐ โ you register a named class that gets an HttpClient injected in the constructor. You encapsulate all the message-sending logic in this class.
- Your business code calls the stronglyโtyped service instead of using HttpClientFactory, URLs and request/response serialization directly in the calling code.
๐ฃ๐ฟ๐ผ๐:
- Encapsulates endpoints in one class
- Strong typing & DIโfriendly
- Easy unitโtesting with mocks/handlers
๐๐ผ๐ป๐:
- Manual mapping between DTOs & endpoints
- Much boilerplate code
- ๐ฅ๐ฒ๐ณ๐ถ๐ โ Refit turns your C# interface into a stronglyโtyped REST client at runtime.
๐ฃ๐ฟ๐ผ๐:
- No boilerplate code for REST calls
- Interfaceโfirst design, clear contracts
๐๐ผ๐ป๐:
- Adds thirdโparty dependency
The images below demonstrate this...