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();
```
Having abstraction (i.e.
IHttpClient) is far better and more praised by the community. It allows you to assignHttpClientas well as your custom-writtenIHttpClientwithout ever changingCatalogService.This is very critical point when creating large systems as your dependencies on concrete implementations decreases, so does the maintenance costs.
Furthermore, using abstractions allows showing what usage was actually intended and reduces the possible distractions. One example:
In this case, you are only using single method, but your service can access tons of unnecessary information, thus distracting from the goal. And to create
MyService, its creator must be able to create instance ofMyClass.Now image
MyServiceis written likeNow, the purpose of
_myInterfaceis clear - you only need a specific subset of methods.MyServiceonly has access to that single method and isn't distracted by all the possible implementation details.