Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient as singleton in dotnet core

On the full framework there was a pattern that came out making HttpClient a singleton. This is because the existing connections could be reused, however on the full framework there were dns caching issues when doing this. Mostly when you would run httpclient as a singleton on the full framework it would cache the dns results, and you would have to use ServicePointManager to force it to refresh once in a while.

Now dotnet core LTS currently does not have ServicePointManager, so my question is. Can you run HttpClient as a singleton in dotnet core and have it respect DNS updates?

like image 352
TerribleDev Avatar asked May 15 '17 22:05

TerribleDev


2 Answers

I am quoting a post from the link below

"Unfortunately, there's no way to do this with .NET Core today. Either ServicePointManager should be brought over to .NET Core or similar equivalent functionality should be enabled some other way."

Here is the link that might be worth checking: https://github.com/dotnet/corefx/issues/11224

like image 61
Bojidar Lyutskanov Avatar answered Nov 08 '22 10:11

Bojidar Lyutskanov


I'm also using HTTPClient as a singleton and injecting it into the controllers in my .NET Core APIs. I can confirm that ServicePointManager exists in .NET Core Runtime 2.0.5.

I'm using the following, after I've created the request to solve DNS issues.

Uri vRequestUri = new Uri ("https:api.example.com/....");
HttpRequestMessage vRequest = new HttpRequestMessage (HttpMethod.Post, vRequestUri);

ServicePoint vSP = ServicePointManager.FindServicePoint (vRequest.RequestUri);
vSP.ConnectionLeaseTimeout = 60 * 1000; // 1 Minute

For those who are not aware of the DNS problem, the following article would be informative http://byterot.blogspot.com.tr/2016/07/singleton-httpclient-dns.html

like image 1
Hakan Çelik Mk1 Avatar answered Nov 08 '22 10:11

Hakan Çelik Mk1