Azure Functions: Dependency Injection

Can Azure Functions do that? Well, I'm always getting surprised by its power and flexibility. I just came across a pretty cool implementation of dependency injection for Azure Functions and would love to share it here. The package I'm going to use in this post is called AzureFunctions.Autofac.

The source code covered in this post is available here

Steps
  • Ensure you have the latest version of the Azure Functions and Web Jobs Tools extension

  • Create Azure Functions using VS 2017 Version 15.6.6

  • This package doesn't support .NET Core yet, so in this case I'm going to target Azure Functions v1 (.NET Framework)

  • The version of Microsoft.NET.Sdk.Functions I'm using is 1.0.10 just so we don't have conflicts with one of their dependencies: Microsoft.Azure.WebJobs. And also I'm having some trouble running latest version of WebJobs locally (something for me to look into later).

  • Add AzureFunctions.Autofac package, version 2.0.0

  • Create a new AutofacConfig.cs file and configure your DI

public class AutofacConfig
{
    public AutofacConfig()
    {
        DependencyInjection.Initialize(builder =>
        {
            // just the sake of demostration, I'm injecting a simple service
            builder.RegisterType<ServiceOne>().As<IServiceOne>();
        });
    }
}

public class ServiceOne : IServiceOne
{
    public string Execute()
    {
        return "This is a result of an injection";
    }
}

public interface IServiceOne { string Execute(); }
  • We only need now to configure the function itself to use this configuration
// Setting DI config here
[DependencyInjectionConfig(typeof(AutofacConfig))]
public static class Function1
{
    [FunctionName("Function1")]
    public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req,
        TraceWriter log,
        // injecting "service" here
        [Inject] IServiceOne serviceOne)
    {
        return req.CreateResponse(HttpStatusCode.OK, serviceOne.Execute());
    }
}

You can implement some quite complex dependency injection configuration here the same way you would do normally with Autofac.

Now we can run the function by pressing F5 and see if everything works as expected.

And it's just a matter of deploying, you can go to the Azure Portal, create a new Function App and set up continuous deployment by following the wizard in Platform features > Deployment options. Once it's deploy, the result is this:

Your brand new function app with dependency injection is now live

That's it. Hope it helps.

Cheers