Is there any difference between the following 2 scenarios of setting up HttpClient?
Should I prefer one to another?
Typed client:
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();
```
IMO, I will go with passing
HttpClient. The reasons are,CatalogServicereally needs is aHttpClient. The service does not care about how to get a client.CatalogServiceto send requests to two different endpoints,IHttpClientFactoryand implement routing insideCatalogService, but that breaks SRP.CatalogServiceFactory. That factory getsIHttpClientFactorypassed in and implement routing inside. That is also known as Separation of Concerns.