HttpClientFactory如何注入class 核心2.1我没法控制

HttpClientFactory how to inject into class I have no control over core 2.1

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

    }       

当我必须调用我无法控制的 class 时,如何使用 HttpClientFactory

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

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

在Startup.cs、services.AddHttpClient();

来自 https://github.com/dotnet/extensions/blob/master/src/HttpClientFactory/Http/src/DependencyInjection/HttpClientFactoryServiceCollectionExtensions.cs

的扩展方法

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

如果你想在不接受它的class中使用它,你需要在Add*中的lambda中创建HttpClient并将其传入,或者用那个 lambda 注册 HttpClient 本身并让 DI 将它传递给

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

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