blog25

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...


HttpClient 1
HttpClient 2
HttpClient 3
HttpClient 4
HttpClient 5