When starting to play around with Azure Functions, the lack of dependency injection support was pretty annoying. To overcome that issue I created a small library, Autofac On Functions, based on Azure Functions 1.x. Unfortunately it is not possible to generate a nuget package from these sources.

Azure On Function with nuget package available

Yesterday I started to play around with Azure Functions v2. It is available as beta version supporting dotnet standard and .net core. Updating was pretty relaxed beside the fact, that there had been some incompatible changes.

The good news is, packaging assemblies with reference to the Azure Functions SDK is now possible. So here it is:

Nuget Autofac On Functions

This is a quite early state, but it is fully functional and provides exactly the functionality that is necessary. You can also download the sources on github.

What you need to get it running

What do you need to enjoy Azure Functions with dependency injection?

You can just download the sample also from Github here. Nuget package 0.1.5 is referenced. Make sure, you have the latest Azure Functions that supports .net standard on your machine.

Create an Azure Functions project

Simple open Visual Studio, and create a new project. Select “Azure Functions”.

add-azure-function-project

Select type of Azure Function

Azure Functions v2 offers a little more infrastructure, also the dialog to add Azure Functions looks a little different. I didn’t select a storage account as for the sample it is simply not necessary. An http trigger function is going to be created on base of .net standard.

select-function-type

Add dependency to AutofacOnFunctions

Right click your project and select “manage nuget packages”. Search for AutofacOnFunctions under “browse”. Install current version. Again, be aware that it “only” supports .net standard.

install-package

Add a test service

With above steps, Visual Studio created an Azure Function. Nuget package is there. What do I need to do to use Dependency Injection now?

Create a simple service to be injected into your http triggered Azure Function and the interface:

namespace AutofacOnFunctions.Sample.Services.Functions
{
    public class TestIt : ITestIt
    {
        public string Name { get; set; }

        public string CallMe()
        {
            return "Dependency Injection Test method had been called.";
        }
    }
}
namespace AutofacOnFunctions.Sample.Services.Functions
{
    public interface ITestIt
    {
        string Name { get; set; }
        string CallMe();
    }
}

Add a Bootstrapper

The bootstrapper will tell the framework which modules need to be loaded, thus which services shall be registered.

using Autofac;
using AutofacOnFunctions.Services.Ioc;
using AutofacOnFunctions.Sample.Services.Modules;

namespace AutofacOnFunctions.Sample.Bootstrap
{
    public class Bootstrapper : IBootstrapper
    {
        public Module[] CreateModules()
        {
            return new Module[]
            {
                new ServicesModule()
            };
        }
    }
}

Certainly, the “ServiceModule” contains your newly created test service:

using Autofac;
using AutofacOnFunctions.Sample.Services.Functions;

namespace AutofacOnFunctions.Sample.Services.Modules
{
    public class ServicesModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<TestIt>().As<ITestIt>();
        }
    }
}

Inject your service in Azure Functions

Use the InjectAttribute to let your service being injected by Autofac.

using AutofacOnFunctions.Services.Ioc;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;

namespace AutofacOnFunctions.Sample.Services.Functions
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]
            HttpRequest req, TraceWriter log,
            [Inject] ITestIt testit)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return new OkObjectResult($"Hello. Dependency injection sample returns '{testit.CallMe()}'");
        }
    }
}

See the Results

Just hit f5 and let’s see the results.

started-function

Custom provider for the InjectAttribute had been loaded. The provider will only be loaded, when there is at least one Inject attribute used. If an inject attribute is used, but there is no bootstrapper available, the framework will raise an exception as the Azure Function will not be able to start.

When you copy the marked url above and paste it in the browser of your choice, you should see this result:

function-result

Finally find all sources in this repository. Enjoy!

Final thoughts

I had an very interesting chat about property vs method injection within Azure Functions with Justin Yoo. You can follow the chat in his latest post Dependency Injection on Azure Functions. The actual question is: Does it make sense due to the static nature of Azure Functions to use method injection? Constructor injection certainly is not sensibly possible, would property injection be the better choice?

Actually I do like Justin’s approach with the FunctionFactory. To keep changes on method signatures low and therefore keep the effort in maintaining unit tests low, I would prefer to just inject the FunctionFactory instead of having a different approach.

I am going to set up a sample and let you guys know.

Azure Functions Dependency Injection: Autofac On Functions nuget Package

2 thoughts on “Azure Functions Dependency Injection: Autofac On Functions nuget Package

  • June 13, 2018 at 1:05 pm
    Permalink

    Nice approach. Of the various ways I’ve seen folks attempting to solve Azure Functions, DI this one feels the most polished. Thanks!

    Reply
    • June 13, 2018 at 2:17 pm
      Permalink

      Many thanks, Troy!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.
Seo wordpress plugin by www.seowizard.org.