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
{
[FunctionName("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
Startup
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)
{
builder.Services.AddHttpClient();
}
}
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.
Notes
* Maybe not exactly ‘natively’
References
https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-dependency-injection