1

After years writing .NET Framework 4.x web apps I'm finally trying to get to grips with writing new apps in .NET 6. Obviously one of the new features I'm keen to make use of is the native dependency injection.

I'm trying to work out how to create a typed HttpClient instance specific to an external web service which I will be calling throughout my application by injecting it as a dependency into my MVC application's controllers. Just about every article and tutorial I've read describes how to use AddHttpClient() in Program.cs and IHttpClientFactory in controller constructors to achieve this.

However, Microsoft's HttpClient guidelines state

In .NET Core and .NET 5+: Use a static or singleton HttpClient instance... This solves both the port exhaustion and DNS changes problems without adding the overhead of IHttpClientFactory

and

If your app requires cookies, consider disabling automatic cookie handling or avoiding IHttpClientFactory. Pooling the HttpMessageHandler instances results in sharing of CookieContainer objects. Unanticipated CookieContainer object sharing often results in incorrect code.

My MVC web app is using cookies, so it sounds like I want to avoid IHttpClientFactory. Is that right? If so, I'd expect to see it mentioned more in the various articles I've read. And, if it is right, what would be the correct way to create typed HTTP Client without using IHttpClientFactory?

Philip Stratford
  • 4,513
  • 4
  • 45
  • 71
  • This is addressed in the comments of the accepted answer here: https://stackoverflow.com/questions/65227400/do-pooled-httpclient-instances-keep-the-cookiecontainer – thewallrus Nov 16 '22 at 02:03
  • _"My MVC web app is using cookies"_ - Can you clarify what this means? Are you saying that the web requests you intend to make with `HttpClient` need to receive and send cookies? It's just the way you phrased it makes me think you're using cookies for authentication, but potentially not using them in web requests you make with `HttpClient`. – ProgrammingLlama Nov 16 '22 at 03:59
  • @ProgrammingLlama Your hunch is absolutely correct. My app is using cookies for authentication (and potentially other things in the future), but not for web requests I'm making with `HttpClient`. Your question, combined with the comment from @thewallrus, has helped me realise I was misunderstanding the warning in the docs, although I feel it could be more clearly worded. Thank you! – Philip Stratford Nov 16 '22 at 09:45

0 Answers0