Roadmap › ASP.NET Core Web API & REST › Module: Performance, Versioning and Docs
Lessons in this course (15)

13. HttpClient correctly: IHttpClientFactory and resilience

Advanced★ Must knowLesson 13 of 15
csharp
builder.Services.AddHttpClient<IWeatherClient, WeatherClient>(c =>
{
    c.BaseAddress = new Uri("https://api.weather.example/");
    c.Timeout = TimeSpan.FromSeconds(10);
}).AddStandardResilienceHandler();

public class WeatherClient(HttpClient http) : IWeatherClient
{
    public Task<Forecast?> GetAsync(string city, CancellationToken ct) =>
        http.GetFromJsonAsync<Forecast>($"forecast?city={Uri.EscapeDataString(city)}", ct);
}
  • new HttpClient() per request → socket exhaustion (sockets stay in TIME_WAIT). One static HttpClient forever → stale DNS.
  • IHttpClientFactory pools and recycles HttpMessageHandlers (default lifetime 2 minutes) — solves both. (Alternatively a singleton HttpClient with SocketsHttpHandler.PooledConnectionLifetime.)