Azure Functions – Dependency Injection

Dependency Injection is a daily task for Developers following SOLID principles but it might surprise you to know DI wasn’t initially supported in Azure Functions by Microsoft. I’ve previously done a post on Autofac which is a great tool for DI if you need third party support, but as of May 2019, Microsoft added official support for DI for Functions v2 onwards. Heres how to get started.

Set up the project

Create a new Visual Studio project using the Functions template and select HttpTrigger for your first function.

Right click on solutions and ‘Manage Package for Solutions’. I always update everything to the latest as sometimes the defaults are slightly behind. If this causes issues, just roll it back a version or so. You’ll then want to make sure you have installed the following packages

Adding Dependency Injection To Azure Functions

In your project create a new c# class called Startup.cs in the same folder as your Azure Function. This startup class is the first thing the project does when it startsup, so it is here that you will need to configure any dependencies you have in your project for use later.

using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;
[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient();
//builder.Services.AddSingleton((s) => { return new MyService(); }); //builder.Services.AddSingleton<ILoggerProvider, MyLoggerProvider>(); } }
}

In your Azure Function, make sure you remove the static off of the class. This is easy to miss but very important!

You need to paste in a constructor into your function class for the things you want to inject. This example is using a simple httpClient, but you can inject anything you need, services for your repos, custom logging etc.

private readonly HttpClient _client;
public Function1(HttpClient, httpClient)
{
_client = httpClient;
}

Note: If you get ‘Method must have a return type’ error, you have either not renamed your constructor to match your function class name or you have pasted the constructor into the wrong scope. Check your brackets!

Testing it works

To test our work, we now just need to use it!

Replace the function code with the simple example below. You’ll see that it has access to our private _client and we can use it without any further set up.

[FunctionName("Function1")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req, ILogger log)
{
var response = await _client.GetAsync("https://google.com"); 
string responseMessage = response.StatusCode.ToString(); 
return new OkObjectResult(responseMessage);
}

Run the project and take the URL (usually http://localhost:7071/api/Function1 if you used the same class name as me). Pop it into the browser and see if it works! Assuming your DI worked, you will get a beautiful ‘OK’ (Http Status 200) printed to the browser!
If you have any issues, they will be printed into your Function window with some aggressive red text.

Thats it! Basic Microsoft supported DI in your Azure Functions with no additional set up or third party packages, win. Make sure you use it in all your projects!

1 Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.