'Should I explicitly use the httpClientFactory class as a recommendation when creating and using typed http clients and DI in .NET 6?
I am using NSwag to create typed http clients with interfaces and registering them with DI using AddHttpClient() and injecting them where they need to be used in calling APIs.
I read about some limitations of the httpclient class such as socket exhaustion & not detecting dns changes and the recommendation to use httpClientFactory and its CreateClient method to create httpclients to alleviate these limitations.
I haven't used the httpClientFactory in a new app that I started working on. It's using .NET 6 and my question is.. Is httpClientFactory still a recommended way to use explicitly or is it used implicitly in DI because of the use of AddHttpClient() and I don't have to worry about those limitations? I didn't see a clear direction on how to use typed clients, or http clients in general, and whether .NET 6 has introduced improvements in this area.
Solution 1:[1]
HttpClientcan be injected only inside typed clients- For other usages
IHttpClientFactoryis required
As the docs state for either case underlying infrastructure (HttpMessageHandler) is managed by the framework so in general you don't need to worry about it (unlike when creating and managing HttpClients manually which could lead to incorrect disposal).
Using typed clients registered via HttpClientFactoryServiceCollectionExtensions.AddHttpClient<TClient> handles IHttpClientFactory for you. When adding typed client internally AddTypedClientCore is called which registers resolver via AddTypedClientCore, which uses IHttpClientFactory:
IHttpClientFactory httpClientFactory = s.GetRequiredService<IHttpClientFactory>();
HttpClient httpClient = httpClientFactory.CreateClient(builder.Name);
ITypedHttpClientFactory<TClient> typedClientFactory = s.GetRequiredService<ITypedHttpClientFactory<TClient>>();
return typedClientFactory.CreateClient(httpClient);
Related:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
