Using IHttpClientFactory in NET for Better HTTP Client Management

Listen to this Post

Featured Image
Creating an `HttpClient` manually in .NET can lead to several issues, such as socket exhaustion and improper configuration of base URLs and headers. A better approach is to use IHttpClientFactory, which manages `HttpClient` instances efficiently.

Why Avoid Manual HttpClient Creation?

  1. Socket Exhaustion: Each `HttpClient` creates a new connection, leading to resource depletion.
  2. Configuration Overhead: Manually setting base URLs and headers is error-prone.

Solution: IHttpClientFactory

`IHttpClientFactory` provides named or typed clients, allowing centralized configuration.

Named Client Example

services.AddHttpClient("MyClient", client => 
{ 
client.BaseAddress = new Uri("https://api.example.com"); 
client.DefaultRequestHeaders.Add("Accept", "application/json"); 
}); 

Typed Client Example

public class MyApiClient 
{ 
private readonly HttpClient _client;

public MyApiClient(HttpClient client) 
{ 
_client = client; 
} 
}

services.AddHttpClient<MyApiClient>(client => 
{ 
client.BaseAddress = new Uri("https://api.example.com"); 
}); 

You Should Know: