HttpClientFactory-.NET Standard-调用Web API

时间:2019-04-01 11:54:17

标签: c# asp.net-core httpclient httpclientfactory

我们当前正在使用HttpClient从MVC应用程序中调用Web API。

HttpClient是静态帮助器类的一部分,如下所示

public static class ApiClient
{
    private static HttpClient MyHttpClient()
    {         
        HttpClient client = new HttpClient();               
        ...         
        return client;
    }

    public static T HttpGet<T>(string requestUri)
    {
        using (var client = MyHttpClient())
        {
            ...
        }
    }
}

并从MVC控制器中调用,如下所示:

ApiClient.HttpGet<MyModel>("<<API URL>>");

因此,每当调用ApiClient时,都会打开一个新的基础连接,这不是正确的方法。

我读到HttpClientFactory并读到post,结果导致创建逻辑修改为

private static HttpClient MyHttpClient()
{
    var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
    var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
    var client = httpClientFactory.CreateClient();
    //HttpClient client = new HttpClient();
    ...
    return client;
}

这会阻止即使多次调用也无法打开多个连接吗?

1 个答案:

答案 0 :(得分:3)

Circle功能基于依赖项注入,而静态变量基本上与依赖项注入不兼容。正如文档清楚所示,正确的方法是:

IHttpClientFactory

然后您在public class ApiClient { private readonly HttpClient _client; public ApiClient(HttpClient client) { _client = client; } ... } 中注册此服务:

ConfigureServices

客户端类不应是静态的,也没有理由使其是静态的。