【问题标题】:HttpClientFactory how to inject into class I have no control over core 2.1HttpClientFactory如何注入类我无法控制核心2.1
【发布时间】:2020-02-10 21:30:43
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回复可能是我做错了,但我得到了“无法将 MyGithubclient”转换为 System.Net.Http.HttpClient”
    • 显示目标类ThirdPartyService及其构造函数
    • @developer9969 同时检查基于异常消息所做的更新。
    • 添加了有问题的构造函数
    • @developer9969 好的,您将错误的类型传递给构造函数。我已经做了必要的修复。只需从已解析的依赖项中调用客户端即可。
    【解决方案2】:

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

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

    在您的类中,将IHttpClientFactory 参数添加到您的构造函数。

    如果你想在一个不接受它的类中使用它,你需要在 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

    【讨论】:

    • 。感谢您的回复,您的意思是在“MyGitHubClient”中添加一个构造函数,如 public MyGitHubClient(HttpClientFactory clientfactory) { Client =httpclientFactory; ?? }
    • 如果您可以控制构造函数,您应该在该类的构造函数上使用IHttpClientFactory 参数。如果你不这样做,并且它需要一个 HttpClient,你需要在外面创建 HttpClient 并将其传入。
    • 我可以控制“MyGitHubClient”,但不能控制 ThirdpartyService。所以你能告诉我如何使用这两者吗?谢谢
    • MyGitHubClient 将有一个构造函数public MyGitHubClient(IHttpClientFactory httpClientFactory)ThirdPartyService 将使用 services.AddScoped&lt;IThirdPartyService&gt;(s =&gt; new ThirdPartyService( s.GetRequiredService&lt;IHttpClientFactory&gt;().CreateClient(), ...); 我正在手机上打字,所以请原谅代码。
    猜你喜欢
    • 1970-01-01
    • 2012-09-26
    • 2022-11-17
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2018-06-30
    相关资源
    最近更新 更多