IHttpClientFactory
is a feature introduced in .NET Core to manage and create HttpClient
instances efficiently. It helps to avoid issues like socket exhaustion and allows for better management of HTTP connections. Here’s how you can use IHttpClientFactory
it with an example in a .NET Core application:
- Add HttpClient Configuration in Startup.cs: In your
Startup.cs
file, add the configuration forIHttpClientFactory
in theConfigureServices
method:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddHttpClient("MyApi", client =>
{
client.BaseAddress = new Uri("https://api.example.com/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Add other headers, policies, etc.
});
// ...
}
- Inject and Use IHttpClientFactory in a Service or Controller: Inject
IHttpClientFactory
into your service or controller where you need to make HTTP requests. Here’s an example of a service:
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
public class MyHttpService
{
private readonly IHttpClientFactory _httpClientFactory;
public MyHttpService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<string> GetApiResponseAsync()
{
var client = _httpClientFactory.CreateClient("MyApi");
var response = await client.GetAsync("some-endpoint");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
In this example, IHttpClientFactory
is injected into the MyHttpService
class. The CreateClient("MyApi")
method creates an instance of HttpClient
configured with the settings defined in Startup.cs
.
- Usage in a Controller: You can also use
IHttpClientFactory
in a controller:
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
private readonly MyHttpService _httpService;
public MyController(MyHttpService httpService)
{
_httpService = httpService;
}
[HttpGet("data")]
public async Task<IActionResult> GetData()
{
var data = await _httpService.GetApiResponseAsync();
return Ok(data);
}
}
This example demonstrates how to use IHttpClientFactory
to manage and create HttpClient
instances in a .NET Core application. The key benefits of using IHttpClientFactory
include better performance, efficient connection reuse, and centralized configuration management for HTTP clients.