Tag Archives: HttpClientFactory

Add HttpClientFactory to an Azure Function

Since I first wrote about dependency injection in Azure Functions things have moved on a bit. These days, the Azure Functions natively* support DI. In this post, I’ll cover, probably the most common, DI scenario: adding HttpClientFactory to your project.

I’ll assume that you have an Azure function, and that it looks something like this:

    public static class Function1
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");

I’ll assume that, because that’s the default HTTP Trigger function you get when you select to create a new function.

NuGet Packages

You’ll need a few NuGet packages; first, you’ll need:

Install-Package Microsoft.Extensions.Http

Which will allow you to use the HttpClientFactory. You’ll also need some packages for the DI:

Install-Package Microsoft.Azure.Functions.Extensions
Install-Package Microsoft.NET.Sdk.Functions


If you create a new MVC project, you get a Startup class, which manages all your DI, etc. So we’re going to create one here. Create a Startup.cs class in the function app:

    public class Startup : FunctionsStartup
        public override void Configure(IFunctionsHostBuilder builder)

The Configure method is a member of FunctionsStartup (ctrl-. to add the override). You’ll also need to add the following line outside of the namespace:

[assembly: FunctionsStartup(typeof(FullNamespace.Startup))]

Essentially, FullNamepsace here refers to the fully qualified Startup class in your project. Without this line, nothing will be added to the IoC container.

The AddHttpClient call inside Configure adds HttpClientFactory to your IoC container.

Azure Function

If you have a look at the code above, you’ll notice the class is static. We can’t have constructor injection into a static class (because we can’t have a constructor); let’s change that to an instance class:

        public Function1(IHttpClientFactory httpClientFactory)
            _httpClientFactory = httpClientFactory;

You’ll also need to change the function itself from static to instance:

        public async Task<IActionResult> Run(

That’s it – you can now reference HttpClientFactory from inside your function.


* Maybe not exactly ‘natively’



Using HttpClientFactory

In .Net Framework (prior to .Net Core), HttpClient was something of a pain. You essentially kept it around in a static variable. If you didn’t, and used too many of them, you could end up issues such as socket exhaustion.

I think most people got around this by implementing their own version of a HttpClientFactory… but now you don’t need to.

In this post, I’m covering the simplest possible use case inside an Asp.Net Core application. The articles linked at the bottom of this post go into much more detail.


The first step to using the HttpClientFactory is to add it to the IoC:

        public void ConfigureServices(IServiceCollection services)

Then, simply inject it into your controller; for example:

        public HomeController(ILogger<HomeController> logger,
            IHttpClientFactory clientFactory)
            _logger = logger;
            _clientFactory = clientFactory;

Finally, you request a client like this:

var client = _clientFactory.CreateClient();

Then you can use it as a normal HttpClient:

var result = await client.GetAsync($"https://localhost:22222/endpoint");