0

I have a C# library that makes calls to a restful web service using a HttpClient.

The class library is used inside an MVC application that could run for weeks without being restarted.

Is a singleton a good way of creating the HttpClient so I have just one HttpClient for the very long life of the MVC application?

Bryan
  • 5,065
  • 10
  • 51
  • 68

2 Answers2

0

Please look at Is HttpClient safe to use concurrently?

Here is another article from Henrik F. Nielsen about HttpClient where he says:

"The default HttpClient is the simplest way in which you can start sending requests. A single HttpClient can be used to send as many HTTP requests as you want concurrently so in many scenarios you can just create one HttpClient and then use that for all your requests."

So you can use a singleton with HttpClient if you will use asynchronous methods, like:

CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync

Quick summary:

  • If you have requests that are related (or won't step on eachother) then using the same HttpClient makes a lot of sense.
  • In genral I would recommend reusing HttpClient instances as much as possible.
Community
  • 1
  • 1
Alex Vazhev
  • 1,363
  • 1
  • 18
  • 17
  • Thanks. I read both links. The examples seem to deal with the a single method reusing the HttpClient multiple times. I'm wondering about reusing it for days or weeks across multiple many classes. – Bryan May 10 '16 at 16:53
  • How about requests that uses different set of default headers ? Would you suggest to use a pool of HttpClients ? – Dibzmania Aug 20 '18 at 12:30
-1

I singleton would keep the HttpClient for the life of the application, but I would ask why you want to do that. It is not good practice.

HttpClient implements IDisposable, really it should be disposed after you have used it. A using statement would be an easy way to do that:

using (var client = new HttpClient()) 
{
  // Do something
}

This way you can be sure your resources are all cleaned up when you don't need them. Instantiating a new HttpClient is not particularly expensive, so it would not affect the applications performance.

Dicky
  • 22
  • 1
  • According to the top answer https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed disposing is not necessary – Bryan May 10 '16 at 16:50