简体   繁体   中英

.NET Core: HttpClientFactory: How to configure ConfigurePrimaryHttpMessageHandler without dependency injection?

I have a .NET Core class library. Am creating HttpClient instance using IHttpClientFactory without dependency injection. I have included Microsoft DI nuget package in my class library.

Sample Code #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.
  }
}

Using DI, we can configure custom message handlers: Sample code #2 with DI:

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

I want to add HttpClientHandler to my Sample code #1 without DI. How to configure primary message handler without DI?

I think it's a weird setup that you have, but apart from that, you can probably do something like this:

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.
}

I just checked the implementation of ConfigurePrimaryHttpMessageHandler and chained it into your setup.


My suggestion would be to change your code and properly use DI, as .NET Core heavily relies on this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM