Hi,
Thank you for this HttpClientSample, it helped me a lot to implement HttpClientFactory inside an ASP.NET core 2.2 application.
I used exactly the same implementation as yours, but still, I got a lot of SocketException with this error message :
An attempt was made to access a socket in a way forbidden by its access permissions
As you can see, my app crash every time Azure app service plan TCP connection limit has been reached (seems to be 700 for B1 plan) :
Steve Gordon said this :
When you add a typed client it will be registered as a transient service in Dependency Injection, so you will always get a fresh instance with a fresh HttpClient created for you by the factory. The factory will manage the underlying handler lifetime for that HttpClient instance, re-using a handler (and connection) if available.
HttpClientFactory is not supposed to address those issues and handle lifetime management of underlying resources like TCP connections ? What do you recommend ?
Microsoft documentation stated :
Therefore, HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. That issue will result in SocketException errors. Possible approaches to solve that problem are based on the creation of the HttpClient object as singleton or static, as explained in this Microsoft article on HttpClient usage.
But there’s a second issue with HttpClient that you can have when you use it as singleton or static object. In this case, a singleton or static HttpClient doesn’t respect DNS changes, as explained in this issue at the .NET Core GitHub repo.
To address those mentioned issues and make the management of HttpClient instances easier, .NET Core 2.1 introduced a new HttpClientFactory that can also be used to implement resilient HTTP calls by integrating Polly with it.
Maybe I could try using typed clients from a singleton service like as it is described here :
https://www.stevejgordon.co.uk/ihttpclientfactory-patterns-using-typed-clients-from-singleton-services
But I'm not sure if it's the best way for my application. I'm developing a status website for an online game, who makes requests day and night to the game's API to get the status of the backend servers. This application is often under heavy loads during game maintenance or downtime periods.
The current implementation of this website in production use Node.js but I rewrote it from scratch with ASP.NET core 2.2, I learn at the same time how ASP.NET Core 2 works 😃 The new service is in beta since today and I observe this issue after few hours.
I can share application sources if needed, but it's mostly what you did.
Best Regards.
@stevejgordon