Calling other services with IHttpClientFactory
Most apps call other web APIs. This lesson shows why new HttpClient() in each request causes problems, how IHttpClientFactory and typed clients fix them, and how to add timeouts and retries with the standard resilience handler.
- StartControllerCalls weather.GetAsync(city)
- Step 2Typed clientBuilds the request with the base address
- Step 3Resilience handlerTimeout, retry with backoff, circuit breaker
- Step 4Pooled handlerReuses connections safely
- EndRemote APIReturns JSON, read into Forecast
The problem with new HttpClient()
Creating and disposing an HttpClient for every request leaves sockets open for a while after each call; under load the server runs out of sockets. Keeping one static HttpClient forever avoids that but ignores DNS changes.
IHttpClientFactory solves both: it pools and recycles the underlying handlers, and lets you configure each client in one place.
A typed client
A typed client is a class that receives a configured HttpClient. The rest of the app depends on the class, not on URLs and JSON details.
public class WeatherClient(HttpClient http)
{
public async Task<Forecast?> GetAsync(string city, CancellationToken ct) =>
await http.GetFromJsonAsync<Forecast>($"v1/forecast?city={Uri.EscapeDataString(city)}", ct);
}
builder.Services.AddHttpClient<WeatherClient>(c =>
{
c.BaseAddress = new Uri("https://api.weather.example/");
c.DefaultRequestHeaders.Add("Accept", "application/json");
})
.AddStandardResilienceHandler(); // retries, timeouts, circuit breakerUsing it
public class HomeController(WeatherClient weather, ILogger<HomeController> log) : Controller
{
public async Task<IActionResult> Index(CancellationToken ct)
{
Forecast? forecast = null;
try
{
forecast = await weather.GetAsync("Hyderabad", ct);
}
catch (HttpRequestException ex)
{
log.LogWarning(ex, "Weather service unavailable"); // page still loads
}
return View(forecast);
}
}Resilience
- AddStandardResilienceHandler (package Microsoft.Extensions.Http.Resilience) adds retries with backoff for transient failures, a timeout per attempt and overall, and a circuit breaker.
- Only retry safe calls; a retried POST may create a payment twice unless the API supports idempotency keys.
- Put API keys in configuration and add them in the AddHttpClient setup, never in code.
- Decide what the page shows when the API is down; a slow dependency should not take your site down.
Interview question
Why should you use IHttpClientFactory instead of creating HttpClient instances yourself?
Creating and disposing HttpClient per request can exhaust sockets because connections linger in TIME_WAIT, while a single static instance never picks up DNS changes. IHttpClientFactory pools and rotates the message handlers to avoid both problems, and gives one place to configure base addresses, headers, logging and resilience policies for each client.
Want the full details? Read the official Microsoft documentation for this topic.