AutoRest 生成的客户端没有合适的构造函数来与 services.AddHttpClient() 方法一起使用。那么我们如何解决这个问题呢?
现在我们有了带有这种签名的公共(public)构造函数。
public Client(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
但是因为它有 bool disposeHttpClient 参数,我们不能直接在 AddHttpClient() 方法中使用它来将客户端服务配置到 DI 中。 令我深感遗憾的是,HttpClientFactory 不包含具有此类签名的方法 AddHttpClient 的覆盖版本:
AddHttpClient<IClient>(Func<IServiceProvider, HttpClietn, IClient> configClient)
最佳答案
您需要使用命名客户端,而不是类型化客户端,然后您需要使用工厂重载注册您的 AutoRest 客户端。
services.AddHttpClient("MyAutoRestClient", c =>
{
// configure your HttpClient instance
});
services.AddScoped<MyAutoRestClient>(p =>
{
var httpClient = p.GetRequiredService<IHttpClientFactory>().GetClient("MyAutoRestClient");
// get or create any other dependencies
// set disposeHttpClient to false, since it's owned by the service collection
return new MyAutoRestClient(credentials, httpClient, false);
});
关于c# - 如何将 HttpClientFactory 与 AutoRest 生成的客户端一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112120/