4

我想使用新的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当我必须调用一个我无法控制的类时,我该如何使用?

4

2 回答 2

3

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

services.AddSingleton<IThirdPartyService>(sp => 
    new ThirdPartyService(sp.GetService<MyGitHubClient>().Client, someOtherParamHere)
);
于 2018-06-10T17:07:07.600 回答
2

在 Startup.cs 中,services.AddHttpClient();

来自https://github.com/dotnet/extensions/blob/master/src/HttpClientFactory/Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs的扩展方法

在您的类中,IHttpClientFactory为您的构造函数添加一个参数。

如果你想在一个不接受它的类中使用它,你需要HttpClient在一个 lambda 中创建Add*并传递它,或者HttpClient用那个 lambda 注册自己并让 DI 传递它

services.AddScoped(s => s.GetRequiredService<IHttpClientFactory>().CreateClient())

项目 GitHub 上有一个示例: https ://github.com/dotnet/extensions/blob/master/src/HttpClientFactory/samples/HttpClientFactorySample/Program.cs

于 2018-06-10T17:16:11.343 回答