Junior — Middle
How can you properly implement or configure an HttpClient instance in a project?
sobes.tech AI
Answer from AI
For proper implementation or configuration of an HttpClient instance in a project, it is important to avoid creating a new instance for each request, as this can lead to socket exhaustion and performance degradation.
It is recommended to use a single shared HttpClient instance for the entire application lifecycle or to use HttpClientFactory (in .NET Core and above), which manages the creation and reuse of clients.
Example of using HttpClientFactory in ASP.NET Core:
// In Startup.cs or Program.cs
services.AddHttpClient();
// In the class where HttpClient is needed
public class MyService
{
private readonly HttpClient _httpClient;
public MyService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetDataAsync(string url)
{
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
If HttpClientFactory is not used, you can create a static or singleton instance of HttpClient:
public static class HttpClientProvider
{
public static readonly HttpClient Client = new HttpClient();
}
This way, you ensure connection reuse and avoid performance issues.