How do you deal with CA2000 (Dispose of IDisposable Objects) when the objects are placed in a Dependency Injection container?

291 views Asked by At

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?

1

There are 1 answers

0
user1496062 On

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 .