AzureFunctions.Autofac 3.0.6

Autofac Implementation of DI for Azure Functions

Install-Package AzureFunctions.Autofac -Version 3.0.6
dotnet add package AzureFunctions.Autofac --version 3.0.6
paket add AzureFunctions.Autofac --version 3.0.6
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

Autofac Dependency Injection in Azure Functions

An Autofac based implementation of Dependency Injection based on Boris Wilhelm's azure-function-dependency-injection and Scott Holden's WebJobs.ContextResolver available on NuGet as AzureFunctions.Autofac

Build status

Usage

In order to implement the dependency injection you have to create a class to configure DependencyInjection and add an attribute on your function class.

Configuration

Create a class and add a constructor that takes 1 string argument. The string argument will automatically be passed and runtime and simply needs to be passed through to the initialize method. In the constructor call the DependencyInjection.Initialize method. Perform the registrations as you normally would with Autofac.

    public class DIConfig
    {
        public DIConfig(string functionName)
        {
            DependencyInjection.Initialize(builder =>
            {
                //Implicity registration
                builder.RegisterType<Sample>().As<ISample>();
                //Explicit registration
                builder.Register<Example>(c => new Example(c.Resolve<ISample>())).As<IExample>();
                //Registration by autofac module
                builder.RegisterModule(new TestModule());
                //Named Instances are supported
                builder.RegisterType<Thing1>().Named<IThing>("OptionA");
                builder.RegisterType<Thing2>().Named<IThing>("OptionB");
            }, functionName);
        }
    }

Function Attribute and Inject Attribute

Once you have created your config class you need to annotate your function class indicating which config to use and annotate any parameters that are being injected. Note: All injected parameters must be registered with the autofac container in your resolver in order for this to work.

    [DependencyInjectionConfig(typeof(DIConfig))]
    public class GreeterFunction
    {
        [FunctionName("GreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject]IGoodbyer goodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()}");
        }
    }

Using Named Dependencies

Support has been added to use named dependencies. Simple add a name parameter to the Inject attribute to specify which instance to use.

    [DependencyInjectionConfig(typeof(DIConfig))]
    public class GreeterFunction
    {
        [FunctionName("GreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject("Main")]IGoodbyer goodbye, 
                                              [Inject("Secondary")]IGoodbyer alternateGoodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()} or {alternateGoodbye.Goodbye()}");
        }
    }

Multiple Dependency Injection Configurations

In some cases you may wish to have different dependency injection configs for different classes. This is supported by simply annotating the other class with a different dependency injection config.

    [DependencyInjectionConfig(typeof(DIConfig))]
    public class GreeterFunction
    {
        [FunctionName("GreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject]IGoodbyer goodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()}");
        }
    }

    [DependencyInjectionConfig(typeof(SecondaryConfig))]
    public class SecondaryGreeterFunction
    {
        [FunctionName("SecondaryGreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject]IGoodbyer goodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()}");
        }
    }

Verifying dependency injection configuration

Dependency injection is a great tool for creating unit tests. But with manual configuration of the dependency injection, there is a risk of mis-configuration that will not show up in unit tests. For this purpose, there is the DependencyInjection.VerifyConfiguration method.

It is not recommended to call VerifyConfiguration unless done so in a test-scenario.

VerifyConfiguration verifies the following rules:

  1. That an InjectAttribute is preceeded by a DependencyInjectionConfigAttribute.
  2. That the configuration can be instantiated.
  3. That all injected dependencies in the given type can be resolved with the defined configuration.
  4. Optionally that no redundant configurations exist, i.e. a DependencyInjectionConfigAttribute with no corresponding InjectAttribute.

Simple example of verification

Below is a very simple example of verifying the dependency injection configuration for a specific class:

    DependencyInjection.VerifyConfiguration(typeof(MyCustomClassThatUsesDependencyInjection));

Ignoring redundant configurations

If you don't want to verify rule 4, pass in false as the second parameter to VerifyConfiguration:

    DependencyInjection.VerifyConfiguration(typeof(MyCustomClassThatUsesDependencyInjection), false);

Example unit test to verify an entire project/assembly

For instance, you can use it in a unit test to verify that all classes in your project has dependency injection set up correctly:

    [TestMethod]
    public void TestDependencyInjectionConfigurationInAssembly() {
        var assembly = typeof(SomeClassInYouProject).Assembly;
        var types = assembly.GetTypes();
        foreach (var type in types) {
            DependencyInjection.VerifyConfiguration(type);
        }
    }

Autofac Dependency Injection in Azure Functions

An Autofac based implementation of Dependency Injection based on Boris Wilhelm's azure-function-dependency-injection and Scott Holden's WebJobs.ContextResolver available on NuGet as AzureFunctions.Autofac

Build status

Usage

In order to implement the dependency injection you have to create a class to configure DependencyInjection and add an attribute on your function class.

Configuration

Create a class and add a constructor that takes 1 string argument. The string argument will automatically be passed and runtime and simply needs to be passed through to the initialize method. In the constructor call the DependencyInjection.Initialize method. Perform the registrations as you normally would with Autofac.

    public class DIConfig
    {
        public DIConfig(string functionName)
        {
            DependencyInjection.Initialize(builder =>
            {
                //Implicity registration
                builder.RegisterType<Sample>().As<ISample>();
                //Explicit registration
                builder.Register<Example>(c => new Example(c.Resolve<ISample>())).As<IExample>();
                //Registration by autofac module
                builder.RegisterModule(new TestModule());
                //Named Instances are supported
                builder.RegisterType<Thing1>().Named<IThing>("OptionA");
                builder.RegisterType<Thing2>().Named<IThing>("OptionB");
            }, functionName);
        }
    }

Function Attribute and Inject Attribute

Once you have created your config class you need to annotate your function class indicating which config to use and annotate any parameters that are being injected. Note: All injected parameters must be registered with the autofac container in your resolver in order for this to work.

    [DependencyInjectionConfig(typeof(DIConfig))]
    public class GreeterFunction
    {
        [FunctionName("GreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject]IGoodbyer goodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()}");
        }
    }

Using Named Dependencies

Support has been added to use named dependencies. Simple add a name parameter to the Inject attribute to specify which instance to use.

    [DependencyInjectionConfig(typeof(DIConfig))]
    public class GreeterFunction
    {
        [FunctionName("GreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject("Main")]IGoodbyer goodbye, 
                                              [Inject("Secondary")]IGoodbyer alternateGoodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()} or {alternateGoodbye.Goodbye()}");
        }
    }

Multiple Dependency Injection Configurations

In some cases you may wish to have different dependency injection configs for different classes. This is supported by simply annotating the other class with a different dependency injection config.

    [DependencyInjectionConfig(typeof(DIConfig))]
    public class GreeterFunction
    {
        [FunctionName("GreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject]IGoodbyer goodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()}");
        }
    }

    [DependencyInjectionConfig(typeof(SecondaryConfig))]
    public class SecondaryGreeterFunction
    {
        [FunctionName("SecondaryGreeterFunction")]
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]HttpRequestMessage request, 
                                              TraceWriter log, 
                                              [Inject]IGreeter greeter, 
                                              [Inject]IGoodbyer goodbye)
        {
            log.Info("C# HTTP trigger function processed a request.");
            return request.CreateResponse(HttpStatusCode.OK, $"{greeter.Greet()} {goodbye.Goodbye()}");
        }
    }

Verifying dependency injection configuration

Dependency injection is a great tool for creating unit tests. But with manual configuration of the dependency injection, there is a risk of mis-configuration that will not show up in unit tests. For this purpose, there is the DependencyInjection.VerifyConfiguration method.

It is not recommended to call VerifyConfiguration unless done so in a test-scenario.

VerifyConfiguration verifies the following rules:

  1. That an InjectAttribute is preceeded by a DependencyInjectionConfigAttribute.
  2. That the configuration can be instantiated.
  3. That all injected dependencies in the given type can be resolved with the defined configuration.
  4. Optionally that no redundant configurations exist, i.e. a DependencyInjectionConfigAttribute with no corresponding InjectAttribute.

Simple example of verification

Below is a very simple example of verifying the dependency injection configuration for a specific class:

    DependencyInjection.VerifyConfiguration(typeof(MyCustomClassThatUsesDependencyInjection));

Ignoring redundant configurations

If you don't want to verify rule 4, pass in false as the second parameter to VerifyConfiguration:

    DependencyInjection.VerifyConfiguration(typeof(MyCustomClassThatUsesDependencyInjection), false);

Example unit test to verify an entire project/assembly

For instance, you can use it in a unit test to verify that all classes in your project has dependency injection set up correctly:

    [TestMethod]
    public void TestDependencyInjectionConfigurationInAssembly() {
        var assembly = typeof(SomeClassInYouProject).Assembly;
        var types = assembly.GetTypes();
        foreach (var type in types) {
            DependencyInjection.VerifyConfiguration(type);
        }
    }

Release Notes

Adds per-function-invocation resolution of dependencies. Dependencies can be specified as follows:

     SingleInstance() - singleton scoped to the class implementing the function
     InstancePerLifetimeScope() - scoped to the function instance
     otherwise - transient scope

     Updated Microsoft.Data.OData to 5.8.4 in NET Framework project to resolve security issues

Version History

Version Downloads Last updated
3.0.6 661 11/5/2018
3.0.5 4,238 9/18/2018
3.0.4 2,750 8/31/2018
3.0.4-beta1 370 8/31/2018
3.0.3 982 8/26/2018
3.0.2 2,108 8/3/2018
3.0.2-beta04 58 8/1/2018
3.0.2-beta03 50 8/1/2018
3.0.2-beta02 54 8/1/2018
3.0.2-beta 51 8/1/2018
3.0.1 940 6/19/2018
3.0.0 2,314 6/10/2018
2.1.0 10,292 4/6/2018
2.0.0 5,306 11/3/2017
1.1.0 112 10/28/2017