In Microsoft's documentation, in the Named Clients example, they retrieve an HttpClient from the IoC container:
var httpClient = _httpClientFactory.CreateClient("GitHub");
In the Typed Clients example, the service that they register as an HttpClient, GitHubService, creates its own HttpClient:
public class GitHubService
{
private readonly HttpClient _httpClient;
public GitHubService(HttpClient httpClient)
{
_httpClient = httpClient;
...
Then, of course, to use the HttpClient, a consuming class would create an instance of GitHubService.
This leaves me with two questions:
- In the Typed Clients example, is
GitHubServiceactually implementingIHttpClientFactorysince it is creating itsHttpClientdirectly? - Also in the Typed Clients example, what role is the IoC container playing? Couldn't the same be done without registering
GitHubServicewith the IoC container at all?
HttpClientinGitHubService; I should re-word that. However, when a new instance ofGitHubServiceis instantiated, doesn't the caller have to provide anHttpClient? Otherwise, the caller does not meet the requirements ofGitHubService's constructor, no?GitHubServiceinstance (and this code is not necessarily the intended client code), it has to provide anHttpClient. In the case where the caller is also the one creating theGitHubService, providing anHttpClientis also its responsibility. Otherwise, some other code does that work (instantiation), and provides theHttpClientto theGitHubServiceconstructor - and this is the role that the IoC container plays.