1

We have an old system with a lot of code similar below:

using(var httpClient = new HttpClient()){...}

We aren't able to update the code at the moment because that will require some approval from our boss and our client.

Recently we added some feature and we are using Unity for DI and we added the HttpClient as singleton in our DI Container

container.RegisterSingleton<HttpClient>();

and we are injecting the instance in our service. But after we deploy the changes we are getting below errors:

  1. One or more errors occurred. A task was canceled.
  2. SocketException with the message of A connection that was expected to be kept alive was closed by the server. ....

After reading some questions online, I found this HttpClient - A task was cancelled?

Disposing the HttpClient instance can cause following HTTP requests started by other instances of HttpClient to be cancelled!

Does it mean, the using() statements was disposing the instance in DI container?

raniel garcia
  • 69
  • 2
  • 6
  • 2
    If you register the HttpClient as Singleton, you shouldn't dispose it _(ur surround it by using())_. But I wouldn't suggest to register it as a singleton, unless the HttpClient is able to restore the connection _(which it probably isn't able)_. Also sending data on multiple threads to one HttpClient could mix messages up. Use multiple instances for that. `RegisterType<>()` – Jeroen van Langen May 19 '22 at 06:34
  • 2
    Yes you were disposing the HTTP client prematurely. Don't ever dispose something you get provided from the DI. One of the major features of DI is to manage the life time of instances for you. – Good Night Nerd Pride May 19 '22 at 06:34
  • Even I'm not wrapping the HttpClient Instance from DI in using statement? does other using(var httpClient = new HttpClient()){...} will dispose the instance from DI? – raniel garcia May 19 '22 at 06:51

0 Answers0