我很好奇这HttpClientFactory
堂课的目的是什么.没有描述MSDN上存在的原因(参见链接).
有些Create
方法有更专业的参数,但大多数我不知道没有参数的调用和普通的构造函数之间有什么区别.
var httpClient = HttpClientFactory.Create();
Run Code Online (Sandbox Code Playgroud)
VS
var httpClient = new HttpClient();
Run Code Online (Sandbox Code Playgroud)
在大多数示例中,我看到使用了new HttpClient()
,没有任何using
语句,即使HttpClient
该类派生自IDisposable
.
由于HttpClient
该类源自IDisposable
,工厂是否有一些池化或缓存?是否有性能优势,或者无关紧要?
我的服务定义:
var host = new HostBuilder().ConfigureServices(services =>
{
services
.AddHttpClient<Downloader>()
.AddPolicyHandler((services, request) =>
HttpPolicyExtensions
.HandleTransientHttpError()
.Or<SocketException>()
.Or<HttpRequestException>()
.WaitAndRetryAsync(
new[] { TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10) },
onRetry: (outcome, timespan, retryAttempt, context) =>
{
Console.WriteLine($"Delaying {timespan}, retrying {retryAttempt}.");
}));
services.AddTransient<Downloader>();
}).Build();
Run Code Online (Sandbox Code Playgroud)
实施Downloader
:
class Downloader
{
private HttpClient _client;
public Downloader(IHttpClientFactory factory)
{
_client = factory.CreateClient();
}
public Download()
{
await _client.GetAsync(new Uri("localhost:8800")); // A port that no application is listening
}
}
Run Code Online (Sandbox Code Playgroud)
通过此设置,我预计会看到三次尝试查询端点,并将日志消息打印到控制台(我也尝试使用记录器但未成功,为简单起见,这里使用控制台)。
我看到的是未处理的异常消息(我只希望在重试和打印日志后看到),而不是调试消息。
未处理的异常:System.Net.Http.HttpRequestException:无法建立连接,因为目标计算机主动拒绝它。(127.0.0.1:8800) ---> System.Net.Sockets.SocketException (10061): 无法建立连接,因为目标计算机主动拒绝连接。
c# dependency-injection dotnet-httpclient polly httpclientfactory