Advertisement
Intermediate .NET MAUI, Dependency Injection & Services

How do you register and use HttpClient with IHttpClientFactory in MAUI?

Short answer

Call builder.Services.AddHttpClient to register typed or named clients backed by IHttpClientFactory, which manages handler pooling and lifetime. Inject the typed client into services.

Save .NET MAUI mock interview
Advertisement
AModel answer
Call builder.Services.AddHttpClient to register typed or named clients backed by IHttpClientFactory, which manages handler pooling and lifetime. Inject the typed client into services. This avoids socket exhaustion from newing HttpClient and centralizes base addresses and default headers.
builder.Services.AddHttpClient<IApiClient, ApiClient>(c =>
{
    c.BaseAddress = new Uri("https://api.example.com");
    c.Timeout = TimeSpan.FromSeconds(30);
});
Real-world example
An app's API layer gets pooled, correctly-configured HttpClients through the factory rather than one leaked static instance.
Likely follow-ups
  • Why not new up HttpClient? | What is a typed client?
Related topics