HttpClientFactory.Create vs new HttpClient

不想你离开。 提交于 2019-12-17 21:53:27

问题


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?


回答1:


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.




回答2:


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?



来源:https://stackoverflow.com/questions/18976042/httpclientfactory-create-vs-new-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!