Recipe 13.1 · C#
IHttpClientFactory and Typed Clients
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Your application calls a customer API from several places. Under load it starts failing with "Only one usage of each socket address is normally permitted", or it keeps calling an old IP address for hours after the partner moved their service. The base URL is copied into each class, and nobody knows which timeout applies.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not to copy: a new HttpClient per call exhausts sockets under load
public CustomerDto GetCustomer(int id)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.example.com/");
var json = client.GetStringAsync("customers/" + id).Result;
return JsonConvert.DeserializeObject<CustomerDto>(json);
}
}
HttpClient implements IDisposable, so wrapping it in using looks responsible. It is the
wrong lifetime. Disposing the client closes its connection pool, and the closed sockets sit in the
TIME_WAIT state for up to a few minutes. At a few hundred calls a second the server runs out of
ports. The opposite fix, one static HttpClient for the life of the process, solves the sockets
and creates a new problem: connections stay open forever and never see a DNS change. The .Result
blocks a thread and can deadlock in classic ASP.NET.
The improved recipe
Let IHttpClientFactory manage handler lifetimes, and wrap each remote service in a typed client
that receives a configured HttpClient through its constructor.
using System;
using System.ComponentModel.DataAnnotations;
namespace ImproveCode.Http;
public sealed class CustomerApiOptions
{
public const string SectionName = "CustomerApi";
[Required]
public Uri? BaseAddress { get; set; }
[Range(typeof(TimeSpan), "00:00:01", "00:05:00")]
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(30);
}
public sealed record CustomerDto(int Id, string Name, string Email);
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
namespace ImproveCode.Http;
public sealed class CustomerApiClient(HttpClient http)
{
public async Task<CustomerDto?> GetCustomerAsync(
int id, CancellationToken ct = default)
{
using HttpResponseMessage response =
await http.GetAsync($"customers/{id}", ct);
if (response.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
response.EnsureSuccessStatusCode();
return await response.Content
.ReadFromJsonAsync<CustomerDto>(ct);
}
}
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace ImproveCode.Http;
public static class CustomerApiServiceCollectionExtensions
{
public static IHttpClientBuilder AddCustomerApi(
this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<CustomerApiOptions>()
.Bind(configuration.GetSection(
CustomerApiOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
return services.AddHttpClient<CustomerApiClient>((sp, http) =>
{
CustomerApiOptions options = sp
.GetRequiredService<IOptions<CustomerApiOptions>>()
.Value;
http.BaseAddress = options.BaseAddress;
http.Timeout = options.Timeout;
http.DefaultRequestHeaders.UserAgent
.ParseAdd("ImproveCode-CustomerSync/1.0");
});
}
}
The configuration it binds to:
{
"CustomerApi": {
"BaseAddress": "https://api.example.com/v2/",
"Timeout": "00:00:30"
}
}
In Program.cs, one line registers it, and any class can then take CustomerApiClient in its
constructor: builder.Services.AddCustomerApi(builder.Configuration);
How it works
The factory keeps a pool of HttpMessageHandler instances, the objects that own the actual
connections. Each HttpClient it hands out is a cheap wrapper over a pooled handler. Handlers are
recycled after two minutes by default, so connections are eventually reopened and pick up DNS
changes, while the pool keeps sockets from piling up. You get the benefit of a shared client
without its staleness.
AddHttpClient<CustomerApiClient> registers the typed client as transient and configures each
HttpClient it receives with the base address, timeout and headers. All the knowledge about the
remote service lives in two places: the options class and the client class. Callers see
GetCustomerAsync, not URLs.
ValidateOnStart makes the application fail at start-up if BaseAddress is missing, instead of
on the first call at three in the morning. Chapter 6 covers the options pattern in detail.
Two small details save hours. BaseAddress must end with a slash, and relative paths must not
start with one. https://api.example.com/v2/ plus customers/7 gives /v2/customers/7, while
/customers/7 would silently drop the /v2. And the 404 check comes before
EnsureSuccessStatusCode, because "customer does not exist" is an expected answer, not an error.
Variations and pitfalls
- Don't capture a typed client in a singleton. A singleton that takes
CustomerApiClientin its constructor holds one handler forever, which brings back the DNS problem. InjectIHttpClientFactoryinto singletons and create clients when needed. - Console tools without dependency injection. Use one static client with a pooled-connection
lifetime:
new HttpClient(new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(2) }). That gives the same behavior as the factory in one line. - Named clients.
services.AddHttpClient("rates", ...)andfactory.CreateClient("rates")work when a typed class would be overkill. I prefer typed clients because the compiler checks the name. - Testing. A typed client takes an
HttpClient, so a test can pass one built over a stubHttpMessageHandlerthat returns canned responses. No mocking library is needed.
On .NET Framework
Microsoft.Extensions.Http supports .NET Framework 4.6.2 and later, so the factory works in
older apps that use Microsoft.Extensions.DependencyInjection. Without dependency injection, use
one static HttpClient and set ServicePointManager.FindServicePoint(uri).ConnectionLeaseTimeout
to a few minutes so connections are recycled.