Sam*_*Sam 10 c# asp.net dotnet-httpclient ihttpclientfactory
我知道我会因为问这个已经被问过一百万次的问题而被钉死在十字架上,我向你保证我已经看过其中的大部分问题/答案,但我仍然有点卡住。
这是一个支持 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);
});
Run Code Online (Sandbox Code Playgroud)
我有一个将使用它的自定义客户端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
Run Code Online (Sandbox Code Playgroud)
我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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我不确定如何将这个命名传递HttpClient到.MyCustomClientProgram.cs
Ale*_*ova 24
您可以直接在类中注入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>();
Run Code Online (Sandbox Code Playgroud)
然后在你的课堂上:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(IHttpClientFactory factory)
{
_client = factory.CreateClient("XYZ_Api_Client");
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以在注册时传递命名实例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);
});
Run Code Online (Sandbox Code Playgroud)
然后在你的课堂上:
public class MyCustomClient
{
private readonly HttpClient _client;
public MyCustomClient(HttpClient client)
{
_client = client;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
您还可以这样做:
// 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>();
Run Code Online (Sandbox Code Playgroud)
什么AddHttpClient<TClient>(IServiceCollection)是
将 IHttpClientFactory 和相关服务添加到 IServiceCollection 并配置 TClient 类型和命名的 HttpClient 之间的绑定。客户端名称将设置为 TClient 的全名。
您可以在此处找到完整的文档。
| 归档时间: |
|
| 查看次数: |
13444 次 |
| 最近记录: |