HttpClientFactory for Azure Functions v2的可用性

时间:2019-03-06 11:04:40

标签: c# azure azure-functions

我想知道HttpClientFactory或类似产品是否可用于Azure Functions v2。

下面是推荐的内容,但是未显示HttpClientFactory或类似内容。

// Create a single, static HttpClient
private static HttpClient httpClient = new HttpClient();

public static async Task Run(string input)
{
    var response = await httpClient.GetAsync("https://example.com");
    // Rest of function
}

https://docs.microsoft.com/en-gb/azure/azure-functions/manage-connections

下面是一个很好的链接,但是我不确定它是否可以在生产中使用,或者是否提供正式功能。

https://www.tpeczek.com/2018/12/alternative-approach-to-httpclient-in.html

更新

要解决的问题

1提供托管的HttpClient池而不是单个HttpClient,例如ASP.NET CORE 2.2中的HttpClientFactory

1 个答案:

答案 0 :(得分:4)

Using the latest Azure Function v2 runtime, IHttpClientFactory is indeed available to you since the Azure Function v2 runtime has been moved to ASP.Net Core 2.2:

Release v2.0.12265

First, you can provide an implementation for IWebJobsStartup where you will define what services to inject.

Add a reference to the NuGet package Microsoft.Extensions.Http and use the extension method AddHttpClient() so that the HttpClient instance your Azure Functions will receive will come from an IHttpClientFactory.

[assembly: WebJobsStartup(typeof(Startup))]

public sealed class Startup : IWebJobsStartup
{
    public void Configure(IWebJobsBuilder webJobsBuilder)
    {
        webJobsBuilder.Services.AddHttpClient();
    }
}

You can then update your Azure Function by removing the static keywords and add a constructor to enable the injection of the instance of HttpClient built by the internal -I think- DefaultHttpClientFactory instance:

public sealed class MyFunction()
{
    private readonly HttpClient _httpClient;

    public MyFunction(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public void Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "v1/resource/{resourceId}")] HttpRequest httpRequest, string resourceId)
    {
         return OkObjectResult($"Found resource {resourceId}");
    }
}

Update

Since the original answer has been posted, the Azure Functions have been updated and there is a new FunctionStartup class to use instead of IWebJobsStartup:

[assembly: FunctionsStartup(typeof(Startup))]

public sealed class Startup : FunctionsStartup
{
    public void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddHttpClient();
    }
}