.NET Core:HttpClientFactory:如何在不依赖注入的情况下配置ConfigurePrimaryHttpMessageHandler?

ran*_*107 3 c# dependency-injection httpclient .net-core asp.net-core

我有一个 .NET Core 类库。正在使用 IHttpClientFactory 创建 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.
  }
}
Run Code Online (Sandbox Code Playgroud)

使用 DI,我们可以配置自定义消息处理程序:使用 DI 的示例代码 #2:

services.AddHttpClient()

    .ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
        };
    });

Run Code Online (Sandbox Code Playgroud)

我想将 HttpClientHandler 添加到我的示例代码 #1 中,无需 DI。如何在没有 DI 的情况下配置主消息处理程序?

小智 6

我认为你的设置很奇怪,但除此之外,你可能可以这样做:

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.
}
Run Code Online (Sandbox Code Playgroud)

我刚刚检查了它的实现ConfigurePrimaryHttpMessageHandler并将其链接到您的设置中。


我的建议是更改代码并正确使用 DI,因为 .NET Core 严重依赖于此。