Azure Function v2 - 如何将配置加载为单例?

标签 azure azure-functions

我正在将 Azure Function 从 v1 (.NET 4.7) 迁移到 v2 (.NET Standard 2)。在 v1 版本中,我使用了一些静态变量,我从这样的配置中读取这些变量来获取(Cosmos DB 客户端的)单例

private static string cosmosDbUri = ConfigurationManager.AppSettings["CosmosDb.Uri"];
//...
private static MyCosmosDbClient cosmosDbClient = new MyCosmosDbClient(cosmosDbUri, ...);

对于 v2,我将切换到 ConfigurationBuilder 进行配置:

private static IConfigurationRoot config = new ConfigurationBuilder()
                .SetBasePath(context.FunctionAppDirectory)
                .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

现在有一个问题,这需要 ExecutionContext ,当函数执行时我才得到(或知道如何得到)。

所以我的问题是,如何最好地解决这个问题?构建一个 Init(ExecutionContext context) 方法,仅当配置尚未加载时我才会调用该方法,或者是否有更好的方法来执行此操作?

最佳答案

您可以将 context.FunctionAppDirectory 替换为 Environment.CurrentDirectory

至少,它可以在本地工作,并且正是您需要 local.settings.json 工作的地方,因此此更改应该是安全的。

关于Azure Function v2 - 如何将配置加载为单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50470758/

相关文章:

node.js - Azure函数( Node 运行时)找不到模块

c# - Azure ServiceBus 在 Client.Receive() 上返回 null

Azure VM - 端点不起作用

azure - Azure AD 访问 token 中的自定义属性

azure - start_logging 和 run.get_context 之间的区别

azure - 如何在 HTTP 触发器 (POST) 上将 pdf 文件添加到 blob 容器,并在请求正文中包含 pdf

azure - 如何在同一 ARM 模板中授予 VM 对 Key Vault 的访问权限

azure - ASP.NET MVC Core Azure Blob 图像调整器

visual-studio - Visual Studio 2019 重新下载 Azure Function CLI 工具

c# - Azure 应用服务连接超时问题