C# .NET Core:HttpClientFactory:如何配置ConfigurePrimaryHttpMessageHandler而不进行依赖项注入?
我有一个.NET核心类库。我正在使用IHttpClientFactory创建HttpClient实例,而不使用依赖项注入。我已经在类库中包含了MicrosoftDiNuget包 示例代码#1: 我想将HttpClientHandler添加到没有DI的示例代码#1中。C# .NET Core:HttpClientFactory:如何配置ConfigurePrimaryHttpMessageHandler而不进行依赖项注入?,c#,asp.net-core,.net-core,dependency-injection,httpclient,C#,Asp.net Core,.net Core,Dependency Injection,Httpclient,我有一个.NET核心类库。我正在使用IHttpClientFactory创建HttpClient实例,而不使用依赖项注入。我已经在类库中包含了MicrosoftDiNuget包 示例代码#1: 我想将HttpClientHandler添加到没有DI的示例代码#1中。 如何在没有DI的情况下配置主消息处理程序?我认为您的设置很奇怪,但除此之外,您可能还可以执行以下操作: private readonly HttpClient client; public A() { var servic
如何在没有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.
}
私有只读HttpClient;
公共A(){
var serviceProvider=newservicecolection()
.AddHttpClient(“您的HttpClientName”)
.Configure(“您的HttpClientName”,选项=>
options.HttpMessageHandlerBuilderActions.Add(builder=>
builder.PrimaryHandler=新的HttpClientHandler
{
ServerCertificateCustomValidationCallback=(m、crt、chn、e)=>true
}))
.BuildServiceProvider();
var_httpClientFactory=serviceProvider.GetService();
client=\u httpClientFactory.CreateClient();//已创建HttpClient实例
//TODO:添加不带DI的自定义消息处理程序。
}
我刚刚检查了ConfigurePrimaryHttpMessageHandler
的实现,并将其链接到您的设置中
我的建议是更改您的代码并正确使用DI,因为.NET Core严重依赖于此。您的意思是不使用AddHttpClient?您总是可以使用
服务从服务中获取HttpClient
。BuildServiceProvider().GetService()
我能够获取HttpClient。我想添加自定义消息处理程序。如果您使用上述函数,您的消息处理程序将在其中。您还可以使用AddHttpMessageHandler
添加额外的消息句柄示例。在您的示例中,“services”变量是来自DI容器的IServiceCollection类型。我想在没有DI容器的类库中添加处理程序。这很酷。谢谢你的解决方案。当然.NET核心服务依赖于DI,在我当前的场景中,DI将导致重新设计。因此,我只有一个在没有DI的情况下使用HttpClientFactory的用例。
services.AddHttpClient()
.ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
};
});
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.
}