Search code examples
c#asp.netasp.net-mvcsingletonhttpclient

Single HttpClient for application life cycle - How does this single instance of HttpClient ensures that it has responded to correct request?


I have created a single instance of HttpClient in Application_Start event to be reused accross the application in Global.asax.cs

Code in App start:

    protected new void Application_Start()
{
    HttpClientHandler httpClientHandler = new HttpClientHandler();
    string _accessTokenUrl = ConfigurationManager.AppSettings["KongAccessTokenURl"];
    string _adminUrl = ConfigurationManager.AppSettings["KongAdminUrl"];
    base.Application_Start();
    ApplicationWrapper.KongAdminClient = new HttpClient(httpClientHandler)
    {
        BaseAddress = new Uri(_adminUrl)
    };
}

Here ApplicationWrapper.KongAdminClient is a static property.

I have developed a login API and within that api i Invoke Kong gateway api to generate token so that i can create a response with that token for that particular user.

For above purpose i create a new HttpRequestMessage for each request but HttpClient remains same as Microsoft says ..

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8#remarks

My question is that with this same intance how will HttpClient know which thread to respond to ? will this same instance respond appropriately to correct requesting thread under load conditions?


Solution

  • Think about it this way. When you are using the Math.Round function, you are effectively just calling a function that does something - in this case rounding - based on a specific input.

    It might have some constants and other values reused, but they don't change in a way that affects other calls.

    So when you use code like GetAsync you are just calling a method that gets some input and returns a value.