Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I cache and reuse HttpClient created from HttpClientFactory?

We can read here YOU'RE USING HTTPCLIENT WRONG AND IT IS DESTABILIZING YOUR SOFTWARE that we should not create and dispose HttpClient for each http request. Instead, it should be cached and reused (e.g as Singleton in DI container). As well in official .NET documentation for HttpClient:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly.

The recommendation is to use HttpClientFactory, but after looking at:

  public interface IHttpClientFactory
  {
    /// <summary>
    /// Creates and configures an <see cref="T:System.Net.Http.HttpClient" /> instance using the configuration that corresponds
    /// to the logical name specified by <paramref name="name" />.
    /// </summary>
    /// <param name="name">The logical name of the client to create.</param>
    /// <returns>A new <see cref="T:System.Net.Http.HttpClient" /> instance.</returns>
    /// <remarks>
    /// <para>
    /// Each call to <see cref="M:System.Net.Http.IHttpClientFactory.CreateClient(System.String)" /> is guaranteed to return a new <see cref="T:System.Net.Http.HttpClient" />
    /// instance. Callers may cache the returned <see cref="T:System.Net.Http.HttpClient" /> instance indefinitely or surround
    /// its use in a <langword>using</langword> block to dispose it when desired.
    /// </para>
    /// <para>
    /// The default <see cref="T:System.Net.Http.IHttpClientFactory" /> implementation may cache the underlying
    /// <see cref="T:System.Net.Http.HttpMessageHandler" /> instances to improve performance.
    /// </para>
    /// <para>
    /// Callers are also free to mutate the returned <see cref="T:System.Net.Http.HttpClient" /> instance's public properties
    /// as desired.
    /// </para>
    /// </remarks>
    HttpClient CreateClient(string name);
  }

it says that each call will always create a HttpClient instance and caller may cache it.

Each call to IHttpClientFactory.CreateClient is guaranteed to return a new HttpClient instance. Callers may cache the returned instance indefinitely or surround its use in a using block to dispose it when desired.

So question is should I completely rely on HttpClientFactory or I should still cache created HttpClient from it?

In our project we use HttpClientFactory.CreateClient every time we make request and he will still having socket exceptions.

like image 881
mardok Avatar asked Feb 08 '19 17:02

mardok


People also ask

Does Httpclientfactory reuse HttpClient?

Therefore, HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.

Should we reuse HttpClient?

When reading the above it is apparent that you should reuse the same instance of the HttpClient throughout your applications lifetime. In some cases where you use base addresses you can have one for each base address, but it should not be instantiated for each use.

Is Httpclientfactory thread safe?

HttpClient is a mutable object but as long as you are not mutating it, it is actually thread safe and can be shared. A common approach is therefore to register it as a singleton with a DI framework or to create a wrapper around it which holds a static instance.

What is ConfigurePrimaryHttpMessageHandler?

ConfigurePrimaryHttpMessageHandler(IHttpClientBuilder, Func<IServiceProvider,HttpMessageHandler>) Adds a delegate that will be used to configure the primary HttpMessageHandler for a named HttpClient.


1 Answers

HttpClient is only IDisposable because its HttpMessageHandler is IDisposable. In reality, it's the HttpMessageHandler which should be long-lived.

HttpClientFactory works by keeping a long-lived HttpMessageHandler internally. Whenever you ask for a HttpClient, it uses the long-lived HttpMessageHander, and tells the HttpClient not to dispose it when the HttpClient is disposed.

You can see that on GitHub:

public HttpClient CreateClient(string name)
{
    // ...

    // Get a cached HttpMessageHandler
    var handler = CreateHandler(name);

    // Give it to a new HttpClient, and tell it not to dispose it
    var client = new HttpClient(handler, disposeHandler: false);

    // ...

    return client;
}

So, technically it doesn't matter whether you cache the HttpClient or dispose it straight away - disposing it doesn't do anything (because it's been told not to dispose its HttpClientHandler, as that's managed by the HttpClientFactory).

Regarding disposing the HttpClient, MSDN says:

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.

Keeping a single HttpClient instance alive for a long duration is a common pattern used before the inception of IHttpClientFactory. This pattern becomes unnecessary after migrating to IHttpClientFactory.

I suspect the SocketExceptions you're seeing have a different cause. Perhaps ask a new question focussed on them?

like image 123
canton7 Avatar answered Sep 29 '22 09:09

canton7