我知道我会因为问这个问题而被钉死,这个问题已经问过无数次了,我向你保证,我已经看过其中的大部分问题/答案,但我还是有点被困住了。
这是一个支持.NET Core6API的ASP.NET标准2.0类库。
在我的Program.cs中,我创建了一个名为HttpClient的HttpClient:
builder.Services.AddHttpClient("XYZ_Api_Client", config =>
{
var url = "https://example.com/api";
config.BaseAddress = new Uri(url);
});我有一个使用这个HttpClient的定制客户机,我在Program.cs中创建了一个单例MyCustomClient,这样我的存储库就可以使用它了。代码在下面。这就是我陷入困境的地方,因为我不知道如何将我命名的HttpClient传递到MyCustomClient。
builder.Services.AddSingleton(new MyCustomClient(???)); // I think I need to pass the HttpClient to my CustomClient here but not sure how我的CustomClient需要使用这个名为XYZ_Api_Client的HttpClient来完成它的工作:
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的名称传递到Program.cs中的MyCustomClient中。
发布于 2022-04-18 07:32:11
可以在类中直接注入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://stackoverflow.com/questions/71908521
复制相似问题