Autofac Dependency Injection in Azure Function

2019-04-27 12:30发布

I am trying to implement DI using Autofac IOC in Azure function. I need to build the container, but not sure where to put the code to build the container

5条回答
神经病院院长
2楼-- · 2019-04-27 12:46

I did write a blog entry for doing dependency injection with Autofac in Azure Functions. Have a look here: Azure Function Dependency Injection with AutoFac: Autofac on Functions

It follows a similar approach like the one by Boris Wilhelms. Another implementation based on Boris' approach can be found on github: autofac dependency injection

-- update ---

With Azure Function v2 it is possible to create nuget packages based on .net standard. Have a look onto Azure Functions Dependency Injection with Autofac: Autofac on Functions nuget Package

查看更多
做自己的国王
3楼-- · 2019-04-27 12:49

Azure Functions doesn't support dependency injection yet. Follow this issue for the feature request https://github.com/Azure/Azure-Functions/issues/299

查看更多
再贱就再见
4楼-- · 2019-04-27 12:49

You can do it using a custom [inject] attribute. See example here https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/

查看更多
迷人小祖宗
5楼-- · 2019-04-27 12:54

I think for now you would need to do something ugly like:

public static string MyAwesomeFunction(string message)
{
    if (MyService == null)
    {
        var instantiator = Initialize();
        MyService = instantiator.Resolve<IService>();
    }

    return MyService.Hello(message);
}

private static IService MyService = null;

private static IContainer Initialize()
{
    // Do your IoC magic here
}
查看更多
姐就是有狂的资本
6楼-- · 2019-04-27 13:03

While Azure Functions does not support DI out of the box, it is possible to add this via the new Extension API. You can register the container using an IExtensionConfigProvider implementation. You can find a full example DI solution in Azure here https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/.

查看更多
登录 后发表回答