Should HttpClient instances created by HttpClientFactory be disposed?

前端 未结 2 579
再見小時候
再見小時候 2020-12-15 15:33

So, I\'ve registered a named client with the services collection in my Startup.cs:

services.AddHttpClient(someServiceN         


        
2条回答
  •  我在风中等你
    2020-12-15 16:14

    No. You should not dispose of your client. To be more general, you should not dispose of anything retrieved via a DI container, which in ASP.NET Core is by default the service collection. The lifetime is managed by the DI container, so if you dispose of the client, but it's later injected into something, you'll get an ObjectDisposedException. Let the container handle disposal.

    This is actually a common confusion with IDisposable classes. You should personally only implement IDisposable if your class itself owns dependencies. If all its dependencies are injected, you should not implement IDisposable, since it doesn't own anything that needs disposal. Likewise, you should not dispose of anything injected into your class, as it doesn't own those dependencies. Only dispose of things you specifically new up. If you don't see the keyword new, you probably shouldn't be disposing.

提交回复
热议问题