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?
解决方案
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.