Should HttpClient instances created by HttpClientFactory be disposed?

前端 未结 2 571
再見小時候
再見小時候 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:05

    Calling the Dispose method is not required but you can still call it if you need for some reasons.

    Proof: HttpClient and lifetime management

    Disposal of the client isn't required. Disposal cancels outgoing requests and guarantees the given HttpClient instance can't be used after calling Dispose. IHttpClientFactory tracks and disposes resources used by HttpClient instances. The HttpClient instances can generally be treated as .NET objects not requiring disposal.

    Check the source of DefaultHttpClientFactory:

    public HttpClient CreateClient(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException(nameof(name));
        }
    
        var handler = CreateHandler(name);
        var client = new HttpClient(handler, disposeHandler: false);
    
        var options = _optionsMonitor.Get(name);
        for (var i = 0; i < options.HttpClientActions.Count; i++)
        {
            options.HttpClientActions[i](client);
        }
    
        return client;
    }
    

    The instance of HttpMessageHandler stores unmanaged resources of the HttpClient. In the classical scenario the HttpClient creates the instance of HttpMessageHandler and disposes it while itself disposing.

    You can see in the above code that different instances of HttpClient shares single instance of HttpMessageHandler and doesn't dispose it (disposeHandler: false).

    So, the call of the HttpClient.Dispose does nothing. But it's not dangerous.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题