Azure函数中的Autofac依赖注入

问题描述:

我正尝试在Azure函数中使用Autofac IOC来实现DI。 我需要构建容器,但不知道在哪里放置代码来构建容器Azure函数中的Autofac依赖注入

我觉得现在你需要做喜欢的事,丑陋:

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 
} 
+0

这是我现在使用的(尽管是脏的感觉)技术。不确定是否有任何其他选项,直到函数提供了一个可扩展点来注入自己的值 –

Azure函数还不支持依赖注入。按照这一问题的功能请求 https://github.com/Azure/Azure-Functions/issues/299

虽然Azure的功能,不支持DI开箱即用,它可以添加这通过新的扩展API。您可以使用IExtensionConfigProvider实现注册容器。您可以在Azure https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/中找到一个完整的示例DI解决方案。

您可以使用自定义[inject]属性来完成此操作。看到这里的例子https://blog.wille-zone.de/post/azure-functions-proper-dependency-injection/

我写了一个博客文章,用Azure函数中的Autofac进行依赖注入。看看这里: Azure Function Dependency Injection with AutoFac: Autofac on Functions

它遵循类似的方法,如上述鲍里斯威廉姆斯所描述的。 其实还有另一种基于Boris Wilhelms代码的方法。你可以在github上找到它:An Autofac based implementation of Dependency Injection based on Boris Wilhelms Azure Function Dependency Injection Project