mortezasoft / AutofacOnFunctions

Azure Function Autofac Integration

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Autofac On Functions

Azure Function Autofac Integration

For a comprehensive explanation have a look at codingsoul

Goal

Azure functions are by design static. Allow for dependency injection within Azure function with Autofac. The extensible nature of Azure Functions allow for attribute based dependency injection implementation. The attribute is called "Inject". Just add it as a parameter to your function combined with the type and name of the service parameter.

        [FunctionName("TestFunction1")]
        public static async Task<HttpResponseMessage> Run([Inject] IMyService MyService)

How to

Simple create a class based on the IBootstrapper interface. You need to package your references into modules, obviously. Different strategies are not implemented by now.

    public interface IBootstrapper
    {
        Module[] CreateModules();
    }

Just visit the sample to check how easy it is to provide your modularized services in Bootstrapper Sample.

    public class Bootstrapper : IBootstrapper
    {
        public Module[] CreateModules()
        {
            return new Module[]
            {
                new ServicesModule()
            };
        }
    }

The module(s) in question shall contain the services that are necessary for the functions in your project. A sample is provided in ServicesModule Sample.

 public class ServicesModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<MyService>();
        }
    }

The bootstrapper implementations will be read and autofac will be configured when the first function that uses the Inject attribute is called or triggered.

Internally the implementation uses a ServiceLocator. When you need to inject services on the fly, avoid using a direct reference to that static class. IObjectResolver implementation can be injected that avoids this anti-pattern.

About

Azure Function Autofac Integration

License:MIT License


Languages

Language:C# 100.0%