Below is my Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
And controller:
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly HttpClient _httpClient;
private readonly IHttpClientFactory _httpClientFactory;
public TestController(HttpClient httpClient, IHttpClientFactory httpClientFactory)
{
_httpClient = httpClient;
_httpClientFactory = httpClientFactory;
}
[HttpGet]
[Route("getdata")]
public async Task GetData()
{
var baseAddress = "http://youtube.com";
var response = await _httpClient.GetAsync(baseAddress);
var client = _httpClientFactory.CreateClient();
response = await client.GetAsync(baseAddress);
}
}
As you can see I can get an instance of HttpClient
in two ways:
- By Injecting
HttpClient
- By Injecting
IHttpClientFactory
and then_httpClientFactory.CreateClient();
Though I am getting responses using both instances, my question is what is the difference between them? And when to use which one?
CodePudding user response:
If you just post singal request.there's even no difference between injecting an instance of httpclient and creating a instance of httpclient with httpclientfactory .
if you use serval instance of httpclient or reuse httpclient to post mutiple requests,some problems may occor,using httpclient could handle these problems. You could create httpclients with differenet settings as follow:
in startup.cs:
services.AddHttpClient("client_1", config =>
{
config.BaseAddress = new Uri("http://client_1.com");
config.DefaultRequestHeaders.Add("header_1", "header_1");
});
services.AddHttpClient("client_2", config =>
{
config.BaseAddress = new Uri("http://client_2.com");
config.DefaultRequestHeaders.Add("header_2", "header_2");
});
in controller:
var client1 = _httpClientFactory.CreateClient("client_1");
var client2 = _httpClientFactory.CreateClient("client_2");