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 staticHttpClientforever → stale DNS.IHttpClientFactorypools and recyclesHttpMessageHandlers (default lifetime 2 minutes) — solves both. (Alternatively a singletonHttpClientwithSocketsHttpHandler.PooledConnectionLifetime.)