我有一个 .NET Core 类库。我正在使用 IHttpClientFactory 创建没有依赖注入(inject)的 HttpClient 实例。我在我的类库中包含了 Microsoft DI nuget 包。
示例代码#1:
Class A {
private readonly HttpClient client;
public A(){
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
client = _httpClientFactory.CreateClient(); //HttpClient instance created
//TODO: Add custom message handler without DI.
}
}
使用 DI,我们可以配置自定义消息处理程序: 带有 DI 的示例代码#2:
services.AddHttpClient()
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
};
});
我想在没有 DI 的情况下将 HttpClientHandler 添加到我的示例代码 #1。 如何在没有 DI 的情况下配置主消息处理程序?
最佳答案
我认为你的设置很奇怪,但除此之外,你可能可以做这样的事情:
private readonly HttpClient client;
public A() {
var serviceProvider = new ServiceCollection()
.AddHttpClient("YourHttpClientName")
.Configure<HttpClientFactoryOptions>("YourHttpClientName", options =>
options.HttpMessageHandlerBuilderActions.Add(builder =>
builder.PrimaryHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
}))
.BuildServiceProvider();
var _httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
client = _httpClientFactory.CreateClient(); //HttpClient instance created
//TODO: Add custom message handler without DI.
}
我刚刚检查了 ConfigurePrimaryHttpMessageHandler
的实现并将其链接到您的设置中。
我的建议是更改您的代码并正确使用 DI,因为 .NET Core 严重依赖于此。
关于c# - .NET 核心 : HttpClientFactory: How to configure ConfigurePrimaryHttpMessageHandler without dependency injection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63879068/