0

I've been working on a .NET 4.6.1 Web API project. As part of this project, I need to call another Web API and I want to use the HttpClient to do so.

From my research online, you can't rely on just doing a normal HttpClient within a using clause as it doesn't garbage collect correctly and can lead to memory leaks.

E.g., I'm currently using it as follows:

using (HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(CONTENTFUL_TIMEOUT_IN_SECONDS) } )
{
    responseText = await client.GetStringAsync(uri).ConfigureAwait(continueOnCapturedContext:false);
}

But as suggested in other articles from Stack Overflow and others, this leads to memory leaks, and the way around this is to share a single instance of the HttpClient. E.g., check HTTPCLIENT DESTABILIZING YOUR SOFTWARE and HttpClientHandler/HttpClient Memory Leak.

I'm not sure however how to setup a shared "single" instance of the HttpClient from within an WebAPI itself?

Shayan Shafiq
  • 1,447
  • 5
  • 18
  • 25
Steely77
  • 21
  • 1

1 Answers1

0

You should have a look on how to implement singleton pattern. Refer to this.

Then you can create a singleton of HttpClient and make it responsible for all HTTP calls from your API.

Shayan Shafiq
  • 1,447
  • 5
  • 18
  • 25
Ipsit Gaur
  • 2,872
  • 1
  • 23
  • 38