Xamarin Forms Dependeny Injected HttpClient Timeout not working when API is down

GMichael 1 Reputation point
2021-10-03T16:52:28.9+00:00

Hello All,

After some research, I've learned that creating new HttpClients with every request is not a good use of HttpClient. Using Dependency Injection is one of the best solutions. So, I've implemented DI in my Xamarin Forms App, but I'm running into an issue. I have the client-side service as a Singleton and am injecting the httpclient into it. The httpclient timeout property works if the API is running. Unfortunately, when the API is not running, the timeout does not work. It takes over two minutes for an exception to occur even when I set the http timeout to 10 seconds. I'm expecting an exception to occur after the set timeout and a message of something like this, "No connection could be made because the target machine actively refused it...", but again nothing happens until over two minutes. However, if I create a new HttpClient, everything works as expected. I've initialized the timeout property in the Startup file and in the Service constructor, but there's no difference. When the API is not running, the httpclient's timeout does not work. I would really appreciate any help with this. See the link to my sample app below and the article I used as a reference. Please let me know if you have any questions.

Thank you in advance!!!

Sample App

Xamarin Forms Dependency Injection Article

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,325 questions
{count} votes