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
?