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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…