3

According to Microsoft, the best practice for an HttpClient is to maintain a singleton version of an HttpClient (paraphrasing, but that's the upshot. Don't dispose of it immediately). My own testing has show that there are definite advantages to a single instance when doing massive Http operations over recreating an HttpClient for every message. So, naturally, it makes sense to place the HttpClient in a DI container.

    // Initialize the HTTP client.
    HttpClient httpClient = new HttpClient();
    httpClient.Timeout = Timeout.Infinite;
    httpClient.BaseAddress = new Uri("https://localhost");
    serviceCollection.AddSingleton(httpClient);

The problem is that I'm getting warnings from StyleCop: CA2000: Dispose objects before losing scope. Obviously I can suppress, but this bothers me because there are other IDisposable objects that may want to be put in the DI container. Is this warning valid when using a DI pattern? Are there any tricks to dealing with it?

Quark Soup
  • 4,272
  • 3
  • 42
  • 74

1 Answers1

1

Same issue , same thoughts.

What you can do is assign it to a field

eg this.httpClient = new HttpClient();

this is probably not a bad idea anyway for singletons so their is a clear owner outside IOC .

user1496062
  • 1,309
  • 1
  • 7
  • 22