1

There is a lot of talk on the Internet about HttpClient, IHttpClientFactory, DI, socket exhaustion problem, etc.

Can someone explain to me why the HttpClientFactory class (from System.Net.Http.Formatting assembly) is needed and its methods.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
kav
  • 21
  • 2
  • Does this answer your question? [HttpClientFactory.Create vs new HttpClient](https://stackoverflow.com/questions/18976042/httpclientfactory-create-vs-new-httpclient) – devNull Feb 23 '20 at 15:03

1 Answers1

4

System.Net.Http.HttpClientFactory, which is shipped with the Microsoft.AspNet.WebApi.Client NuGet package, is just a helper to create a HttpMessageHandler with a pipeline of multiple HttpDelegatingHandler objects. Its Create method literally does this:

public static HttpClient Create(HttpMessageHandler innerHandler, params DelegatingHandler[] handlers)
{
    HttpMessageHandler pipeline = CreatePipeline(innerHandler, handlers);
    return new HttpClient(pipeline);
}

And the CreatePipeline sets up a single HttpMessageHandler that wrapps all the passed handlers into a single pipeline, so that they get executed in order.

This HttpClientFactory has little to do with the newer IHttpClientFactory that’s part of the Microsoft.Extensions.Http package. That one is what all the “buzz” is about and how you should ideally create HTTP clients in the future.

poke
  • 369,085
  • 72
  • 557
  • 602
  • I'm not using .NET Core 2.1+ so don't have access to `IHttpClientFactory`. Is it better then to use `HttpClientFactory.Create()` instead of using `HttpClient`? – David Klempfner Jan 10 '23 at 23:35
  • 1
    @DavidKlempfner If you only want a standard HttpClient in a legacy .NET Framework application, then you can just create a static `HttpClient` that you reuse yourself. `HttpClientFactory.Create` is only really useful if you need to customize the handler pipelines in some way. – poke Jan 11 '23 at 16:34