我知道我會因為提出這個之前被問過一百萬次的問題而被釘死在十字架上,我向你保證,我已經看過大多數這些問題/答案,但我還是有點卡住了。
這是一個支持 ASP.NET Core 6 API 的 .NET Standard 2.0 類別庫。
在我的Program.cs我創建一個命名的 HttpClient 是這樣的:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
我有一個將使用它的自定義客戶端,HttpClient我在其中創建了一個單例MyCustomClient,Program.cs以便我的存盤庫可以使用它。代碼如下。這是我卡住的地方,因為我不確定如何將我的名字傳遞HttpClient給MyCustomClient.
builder.Services.AddSingleton(new MyCustomClient(???)); // I think I need to pass the HttpClient to my CustomClient here but not sure how
我CustomClient需要使用這個HttpClient命名XYZ_Api_Client來完成它的作業:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(HttpClient client)
{
_client = client;
}
public async Task<bool> DoSomething()
{
var result = await _client.GetAsync();
return result;
}
}
所以我不確定如何將這個命名傳遞HttpClient給MyCustomClient.Program.cs
uj5u.com熱心網友回復:
您可以直接在您的類中注入IHttpClientFactory,然后將命名分配給HttpClient屬性。
注冊工廠和您的定制客戶:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
// no need to pass anything, the previous line registered IHttpClientFactory in the container
builder.Services.AddSingleton<MyCustomClient>();
然后在你的課上:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(IHttpClientFactory factory)
{
_client = factory.CreateClient("XYZ_Api_Client");
}
// ...
}
或者,您可以在注冊時傳遞命名實體MyCustomClient
注冊工廠和您的定制客戶:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});
// specify the factory for your class
builder.Services.AddSingleton<MyCustomClient>(sp =>
{
var factory = sp.GetService<IHttpClientFactory>();
var httpClient = factory.CreateClient("XYZ_Api_Client");
return new MyCustomClient(httpClient);
});
然后在你的課上:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(HttpClient client)
{
_client = client;
}
// ...
}
你也可以這樣做:
// register the named client with the name of the class
builder.Services.AddHttpClient("MyCustomClient", config =>
{
config.BaseAddress = new Uri("https://example.com/api");
});
// no need to specify the name of the client
builder.Services.AddHttpClient<MyCustomClient>();
什么AddHttpClient<TClient>(IServiceCollection)是
將 IHttpClientFactory 和相關服務添加到 IServiceCollection 并配置 TClient 型別和命名 HttpClient 之間的系結。客戶端名稱將設定為 TClient 的全名。
您可以在此處找到完整的檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460907.html
標籤:C# 网 dotnet-httpclient ihttpclientfactory
