2

This thread ask about if the HttpClient created by HttpClientFactory should be cached. I think the answer is no as each HttpClientFactory will existing pool of HttpClientHandler.

But my question is what happen if it is cached and reuse. Does it still have the DNS update problem?

According to Steve Gordon's An Introduction to HttpClientFactory,

Any clients depending on the original handler chain can continue using it without any issues.

I think it means the cached HttpClient will continue use the same HttpClientHandler even after the 2 mins and it won't do the DNS update. If that is the case, the HttpClient should not be cached and should use the HttpClientFactory.CreateClient all the time.

ASP.NET Core doc just says it does not need to keep a single instance, but it does not tell the consequence if a single instance is kept.

Keeping a single HttpClient instance alive for a long duration is a common pattern used before the inception of IHttpClientFactory. This pattern becomes unnecessary after migrating to IHttpClientFactory.

kklo
  • 661
  • 1
  • 8
  • 14
  • 1
    I suspect that by "cached" you mean "keep in a field for long" ? Then yes, and that's what the answers, articles and docs say. It's the handlers that get *cached* in a connection pool. Each client will get a handler from that pool. When the client gets disposed, the handler goes back to the pool and reused. When the 2 minutes pass, the handler is evicted and a new one created. – Panagiotis Kanavos Mar 08 '19 at 09:29
  • BTW that's why the articles don't say "cached" when talking about the HttpClient instance. Caching implies temporary storage and eviction and HttpClientFactory uses an actual cache for the handlers. If you use dependency injection though you won't have to worry about any of these things – Panagiotis Kanavos Mar 08 '19 at 09:33
  • Very detailed discussion of the disposal questions here: https://www.stevejgordon.co.uk/httpclient-creation-and-disposal-internals-should-i-dispose-of-httpclient . I believe you need to obtain a new `HttpClient` each time from `HttpClientFactory`, to avoid the stale DNS issues. Long-duration caching an `HttpClient` obtained from HCF will leave that client vulnerable to stale DNS, I believe. – mountain traveller Mar 08 '19 at 17:36
  • 1
    I do read Steve Gordon's article. The MyGitHubClient keeps the HttpClient as private member and that's what I don't understand why it does it. But I just find out this comment https://www.stevejgordon.co.uk/httpclientfactory-named-typed-clients-aspnetcore#comment-3901853287 where Steve said "When creating these HttpClient based services which have HttpClient injected they should be registered as transient with DI." As it is transient, it's short-lived and can only be used directly in transient style classes such as controllers. – kklo Mar 08 '19 at 18:20

0 Answers0