🌐 HttpClientFactory = Efficient HTTP
HttpClient has problems. HttpClientFactory solves them. Pooling, resilience, named clients.
❌ Manual HttpClient
using var client = new HttpClient();
client.BaseAddress = new Uri("https://api.example.com");
var response = await client.GetAsync("/data");
✅ HttpClientFactory
builder.Services.AddHttpClient();
var client = httpClientFactory.CreateClient();
client.BaseAddress = new Uri("https://api.example.com");
📝 HttpClientFactory Setup
// Program.cs
builder.Services.AddHttpClient();
// Named client
builder.Services.AddHttpClient("GitHub", client =>
{
client.BaseAddress = new Uri("https://api.github.com");
client.DefaultRequestHeaders.Add("User-Agent", "MyApp");
});
// Typed client
builder.Services.AddHttpClient();
// Resilient client (Polly)
builder.Services.AddHttpClient()
.AddTransientHttpErrorPolicy(builder =>
builder.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
// Using factory
public class MyService
{
private readonly IHttpClientFactory _httpClientFactory;
public MyService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task GetDataAsync()
{
var client = _httpClientFactory.CreateClient("GitHub");
return await client.GetStringAsync("/users/octocat");
}
}
💡 HttpClientFactory Benefits
- Connection pooling
- Automatic retry (with Polly)
- Named clients
- Typed clients
- Socket exhaustion prevention
“HttpClientFactory solves HttpClient problems. Pooling, resilience, efficiency. Essential for HTTP calls.”

