14

I want to know if HttpClientFactory or similar is available for Azure Functions v2.

Below is what is recommended, but HttpClientFactory or similar is not shown.

// 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://learn.microsoft.com/en-gb/azure/azure-functions/manage-connections

Below is a good link but I am not sure if it can be used on production, or an official feature is available.

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

Update:

Problem to solve

1 Providing managed HttpClient pool instead of single HttpClient, like HttpClientFactory in ASP.NET CORE 2.2

Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
Pingpong
  • 7,681
  • 21
  • 83
  • 209

1 Answers1

25

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:

Note: You will first need to install the Microsoft.Extensions.Http NuGet package

using MyNamespace.Functions;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[assembly: FunctionsStartup(typeof(Startup))]
namespace MyNamespace.Functions
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            builder.Services.AddHttpClient();
        }
    }
}

Original Answer

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.

using MyNamespace.Functions;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;

[assembly: WebJobsStartup(typeof(Startup))]
namespace MyNamespace.Functions
{
    public class Startup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            builder.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}");
    }
}
Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
Kzryzstof
  • 7,688
  • 10
  • 61
  • 108
  • I am not sue if using single instance of HttpClient is the correct way. part of the thread is to use HttpClient pool – Pingpong Mar 06 '19 at 11:40
  • @Pingpong I have updated the answer so that the `HttpClient` your Azure Function receives is provided to you via `IHttpClientFactory`. – Kzryzstof Mar 06 '19 at 13:01
  • the Run is now instance method, is it static Run() method better? – Pingpong Mar 06 '19 at 17:15
  • @Pingpong I am not sure if instance method makes it better... well, for the testing aspect, I do think it is better. But the real benefit here is the injection part... and somewhat mimics what we have with an ASP.Net Core Controller. – Kzryzstof Mar 06 '19 at 17:51
  • 1
    Thx. Answered!! – Pingpong Mar 06 '19 at 23:33
  • Not sure if you have info on this https://stackoverflow.com/questions/55033813/model-binding-for-function-parameters-for-http-request-with-c-sharp-in-azure-fuc – Pingpong Mar 06 '19 at 23:34
  • This answer is out of data and appears to be broken. IWebJobsStartup should be FunctionsStartup, etc. https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection You could provide a full working example vs what you have above. – Chris Weber May 28 '19 at 20:52
  • @ChrisWeber Thanks for the heads up. I have added the newer stuff. – Kzryzstof May 28 '19 at 22:17
  • 5
    For n00bs like me, I thought I'd add you also need to install the Nuget package Microsoft.Extensions.Http or you'll get the error _IServiceCollection does not contain a defintion for AddHttpClient_ – pcdev Jun 10 '19 at 10:18
  • So I took your advice using the FunctionStart up way instead of the web jobs way. When the functions start up I get this error "Method not found: 'Microsoft.Extensions.DependencyInjection.IServiceCollection Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder.get_Services()'." I notice I only get this error if I have builder.Services.AddHttpClient(); inside the method. Any takes on this guys? –  Pat Aug 28 '19 at 16:42
  • @Pat Do you have all the [prerequisites](https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection#prerequisites)? – Kzryzstof Aug 28 '19 at 18:49
  • 1
    Yes. I figured out I was using a Preview version of the Microsoft.Extensions.DependencyInjection.Abstractions Once I rolled that back to last stable everything worked –  Pat Aug 28 '19 at 22:05