1

In our .NET API, we were creating the HttpClient instances in each controller action. As the application should have a single instance of HttpClient for each HTTP endpoint it consumes.

We have got a couple of options.

  • Create a base controller class with public readonly static HttpClient httpClient = new HttpClient() and inherit all the controllers from this.
  • Each controller should have it's own private readonly static HttpClient httpClient = new HttpClient() declaration.

I am not sure if this will impact the performance (when thousands of users hit the application). Can anyone guide me to follow the right approach, please?

A J Qarshi
  • 2,772
  • 6
  • 37
  • 53
  • 2
    Either 1) Use `HttpClientFactory`, which manages the lifetimes of the handlers appropriately, or 2) Use .NET Core 2.1+, in which case the lifetime issues of `HttpClient` more-or-less go away, and you can just use normal instances. There are other advantages to using `HttpClientFactory` in ASP.NET applications – canton7 May 11 '21 at 09:58
  • 1
    Compulsory reading: https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ – Matt Evans May 11 '21 at 10:15
  • ... but note that the issues described there were fixed in SocketsHttpHandler, which became the default handler in .NET Core 2.1 – canton7 May 11 '21 at 10:16
  • 1
    OP specified .net-4.6 – Matt Evans May 11 '21 at 10:17
  • Sure, just worth noting that the issues there were fixed 3 years ago – canton7 May 11 '21 at 10:23
  • 1
    Our application is based on .net-4.6. – A J Qarshi May 11 '21 at 10:25
  • There is an approach specified for the .Net 4.6.2 in this post. Shall we follow the same for our application if we want to use the `HttpClientFactory` https://stackoverflow.com/a/51499006/641103 – A J Qarshi May 11 '21 at 10:27
  • @AJQarshi Yes indeed that's the preferred way. The `AddHttpClient` [registers](https://github.com/aspnet/HttpClientFactory/blob/master/src/Microsoft.Extensions.Http/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs#L37) the `DefaultHttpClientFactory` for `IHttpClientFactory`. Then you can retrieve that from the DI container. – Peter Csala May 13 '21 at 07:43

0 Answers0