下面2个设置HttpClient的场景有什么区别吗?
我应该更喜欢一个吗?
打字客户端:
public class CatalogService
{
private readonly HttpClient _httpClient;
public CatalogService(HttpClient httpClient) {
_httpClient = httpClient;
}
public async Task<string> Get() {
var response = await _httpClient.GetAsync();
....
}
public async Task Post() {
var response = await _httpClient.PostAsync();
...
}
}
// Startup.cs
//Add http client services at ConfigureServices(IServiceCollection services)
services.AddHttpClient<ICatalogService, CatalogService>();
IHttpClientFactory:
public class CatalogService
{
private readonly IHttpClientFactory _factory;
public CatalogService(IHttpClientFactory factory) {
_factory = factory;
}
public async Task<string> Get() {
var response = await _factory.CreateClient().GetAsync();
....
}
public async Task Post() {
var response = await _factory.CreateClient().PostAsync();
...
}
}
// Startup.cs
//Add http client services at ConfigureServices(IServiceCollection services)
services.AddHttpClient();
```