HttpClientFactory.Create vs new HttpClient

后端 未结 4 1144
小鲜肉
小鲜肉 2020-12-02 12:20

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 spec

相关标签:
4条回答
  • 2020-12-02 12:53

    As mentioned in

    https://docs.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.

    0 讨论(0)
  • 2020-12-02 13:03

    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.

    0 讨论(0)
  • 2020-12-02 13:05

    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

    0 讨论(0)
  • 2020-12-02 13:12

    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?

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