Should Httpclient Be Transient or Singleton?

Should Httpclient Be Transient or Singleton?

The HttpClient class is more suitable as a singleton for a single app domain. This means the singleton should be shared across multiple container classes. With this tactic, you do get a singleton, but this makes it difficult to share. The HttpClient class implements the IDisposable interface.

Should we create a new single instance of HttpClient for all requests?

Although it implements the IDisposable interface it is actually a shared object. This means that under the covers it is reentrant and thread safe. Instead of creating a new instance of HttpClient for each execution you should share a single instance of HttpClient for the entire lifetime of the application.

Should you reuse HttpClient?

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. This will result in SocketException errors.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.