我想使用新的HttpClientFactory
,但我无法设置它。
我有以下内容(我将整理好的例子放在一起解释我的观点)
public class MyGitHubClient
{
public MyGitHubClient(HttpClient client)
{
Client = client;
}
public HttpClient Client { get; }
}
然后在webapi.Startup
我有
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient<MyGitHubClient>(client =>
{
client.BaseAddress = new Uri("https://api.github.com/");
//etc..
});
//NOW I get error "Class name is not valid at this point" for "MyGitHubClient" below
services.AddSingleton<IThirdPartyService>(x => new ThirdPartyService(MyGitHubClient,someOtherParamHere));
///etc...
}
第三方构造函数
public ThirdPartyService(HttpClient httpClient, string anotherParm)
{
}
当我必须调用一个我无法控制的课程时,如何使用HttpClientFactory
?
答案 0 :(得分:2)
原始问题中使用的AddSingleton
委托将IServiceProvider
作为参数参数。使用提供程序来解析所需的依赖关系
services.AddSingleton<IThirdPartyService>(sp =>
new ThirdPartyService(sp.GetService<MyGitHubClient>().Client, someOtherParamHere)
);
答案 1 :(得分:0)
在Startup.cs中,IHttpClientFactory
在您的班级中,向构造函数添加HttpClient
参数。
如果要在不接受它的类中使用它,则需要在Add*
中的lambda中创建HttpClient
并将其传入或注册services.AddScoped(s => s.GetRequiredService<IHttpClientFactory>().CreateClient())
与lambda一起让DI传递它
function putStars(){
if(test){
for(var i = 0; i < 5; i++){
var star = document.createElement("img");
star.src = "star.png";
var element = document.querySelector(".java");
element.append(star);
}
test = false;
}
}
项目GitHub上有一个例子: https://github.com/aspnet/HttpClientFactory/blob/dev/samples/HttpClientFactorySample/Program.cs