HttpClientFactory如何注入到类I中,无法控制核心2.1

时间:2018-06-10 16:09:19

标签: c# asp.net-core asp.net-core-webapi asp.net-core-2.1 httpclientfactory

我想使用新的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

2 个答案:

答案 0 :(得分:2)

原始问题中使用的AddSingleton委托将IServiceProvider作为参数参数。使用提供程序来解析所需的依赖关系

services.AddSingleton<IThirdPartyService>(sp => 
    new ThirdPartyService(sp.GetService<MyGitHubClient>().Client, someOtherParamHere)
);

答案 1 :(得分:0)

在Startup.cs中,IHttpClientFactory

https://github.com/aspnet/HttpClientFactory/blob/dev/src/Microsoft.Extensions.Http/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs

的扩展方法

在您的班级中,向构造函数添加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