![](/img/trans.png)
[英]How do I configure a DbContext with dependency injection with .Net Core 2.1?
[英].NET Core: HttpClientFactory: How to configure ConfigurePrimaryHttpMessageHandler without dependency injection?
我有一個 .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.
}
}
使用 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 嚴重依賴於此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.