78

I am curious what is the purpose of the HttpClientFactory class. There is no description of why it exists on MSDN (see link).

There are Create methods with more specialized arguments, but mostly I wonder what is the difference between the call with no parameters and the normal constructor.


var httpClient = HttpClientFactory.Create();

VS

var httpClient = new HttpClient();

In most examples I see the use of new HttpClient(), without any using statements, even though the HttpClient class derives from IDisposable.

Since the HttpClient class derives from IDisposable, is there some pooling or caching done by the factory? Are there performance benefits, or does it not matter?

Update – IHttpClientFactory in .NET Core 2.1

Please note that since this question was asked, newer versions of .NET have been released, and .NET Core 2.1 introduced a new and much improved approach for getting a HTTP client.

Refer to Ali Bayat's answer below for using IHttpClientFactory instead with .NET Core.

However, I'm keeping Darrel Miller's answer as the accepted answer since this is the correct answer for usage in .NET Framework up to v4.8, for which this question was asked.

With .NET 5 the discrepancy between .NET Framework and .NET Core will be aligned, and you should use IHttpClientFactory instead.

Update – Official guidance

Microsoft has added documentation regarding the disposal behavior and recommended use: https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/httpclient-guidelines

Bart Verkoeijen
  • 16,545
  • 7
  • 52
  • 56

4 Answers4

71

The factory is helper method to assist in the creation of a client when you have more than one DelegatingHandler in the pipeine. Delegating handlers need to be connected together to form a pipeline. This factory allows you to pass the handlers in as an array and the factory will take care of connecting them together.

I believe, and don't take my word for it, that the CreatePipeline method may be used over on the server side to build the message handling pipeline for a Web API HttpServer.

I'm happy you are not seeing many examples of using blocks around HTTPClient as I have been fighting against this practice for what feels like years. Although HttpClient does implement disposable it only does it to handle exceptions scenarios where it gets destroyed while a request is ongoing. HttpClient instances should be long lived. Disposing them forcibly closes the underlying TCP connection that is supposed to be pooled. HttpClient is thread safe and can be safely used many times by different threads. That's how it is intended to be used, not the single use, using block pattern that I see regularly.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • 1
    Thanks for your response! After digging deeper, I also came across [this SO post](http://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed) in which David Faivre explains about a problem that can occur when newing up too many `HttpClient`s repeatedly. – Bart Verkoeijen Sep 26 '13 at 07:44
  • @Darrel so if i have a long running HttpClient but eventually I am going to get rid of it, at that time do I need to manually call dispose or can i just let it fall out of scope and let the GC take care of it? – SlaterCodes Dec 10 '13 at 22:43
  • 4
    @Darrel, please note that although most of the methods are thread-safe, instance members are not (as is the case in most of the .NET Framework) - see http://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx – Dave Black Oct 13 '14 at 22:16
  • What about not named clients (Ex: for different baseUrls), so does httpCLientFactory.Create() have all benefits as named clients (not speaking about custom settings and features like Polly)? – Ssss Jun 25 '21 at 15:00
36

IHttpClientFactory offers the following benefits:

  1. Naming and configuring logical HttpClient instances.
  2. Build an outgoing request middleware to manage cross-cutting concerns around HTTP requests.
  3. Integrates with Polly for transient fault handling.
  4. Avoid common DNS problems by managing HttpClient lifetimes.
  5. Adds logging for all requests sent through clients created by the factory.

more

Ali Bayat
  • 3,561
  • 2
  • 42
  • 43
  • 2
    Thank you for adding this guidance, since with the introduction of `IHttpClientFactory` in .NET Core, it is a much better alternative to the options available at the time this question was asked. – Bart Verkoeijen Feb 27 '20 at 09:17
  • 2
    I'm curious is there an actual class in .NET Core that implements IHttpClientFactory, a concrete? The only way to use it appears to be using the IoC container and calling services.AddHttpClient() – bytedev Mar 24 '20 at 09:05
  • 1
    IHttpClientFactory is an interface implemented by DefaultHttpClientFactory – Ali Bayat Mar 24 '20 at 12:31
  • 3
    @bytedev As of today there still doesn't seem be a way of using the concrete implementation without being reliant on Microsoft's own DI container. There is an ongoing discussion about this issue over here: https://github.com/dotnet/aspnetcore/issues/28385 – silkfire May 13 '21 at 22:26
  • 1
    @AliBayat `DefaultHttpClientFactory` is an internal class, so you can't instantiate it from your own code. – silkfire May 13 '21 at 22:27
7

As mentioned in

https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net-core

The

default constructor for HttpClient

has sockets exhaustion and DNS changes issues, which are addressed by IHttpClientFactory. It also provide extensions for adding resiliency to the application.

Deepak Mishra
  • 2,984
  • 1
  • 26
  • 32
0

Let me add to @DarrelMiller's answer:

You should pay attention to the lifetime of your HttpClient instances if scaling is of any importance to you. Please refer to What is the overhead of creating a new HttpClient per call in a WebAPI client?

Dave Black
  • 7,305
  • 2
  • 52
  • 41