Warm tip: This article is reproduced from serverfault.com, please click

其他-Azure Function IWebJobsStartup 实现中的 ExecutionContext

(其他 - ExecutionContext in Azure Function IWebJobsStartup implementation)

发布于 2019-04-10 15:57:37

如何访问 Functions Startup 类中的 ExecutionContext.FunctionAppDirectory 以便我可以正确设置我的配置。请看下面的启动代码:

[assembly: WebJobsStartup(typeof(FuncStartup))]
namespace Function.Test
{
    public class FuncStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            var config = new ConfigurationBuilder()
               .SetBasePath(“”/* How to get the Context here. I cann’t DI it 
                           as it requires default constructor*/)
               .AddJsonFile(“local.settings.json”, true, reloadOnChange: true)
               .AddEnvironmentVariables()
               .Build();

        }
    }
 }
Questioner
Soma Yarlagadda
Viewed
0
Alex AIT 2019-04-11 03:29:36

你没有,ExecutionContext因为你的 Azure 函数尚未处理实际的函数调用。但是你也不需要它 - local.settings.json 会自动解析为环境变量。

如果确实需要该目录,可以%HOME%/site/wwwroot在 Azure 中使用,并AzureWebJobsScriptRoot在本地运行时使用。这相当于FunctionAppDirectory.

也是关于这个话题的一个很好的讨论。

    public void Configure(IWebJobsBuilder builder)
    {
        var local_root = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
        var azure_root = $"{Environment.GetEnvironmentVariable("HOME")}/site/wwwroot";

        var actual_root = local_root ?? azure_root;

        var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
            .SetBasePath(actual_root)
            .AddJsonFile("SomeOther.json")
            .AddEnvironmentVariables()
            .Build();

        var appInsightsSetting = config.GetSection("APPINSIGHTS_INSTRUMENTATIONKEY");
        string val = appInsightsSetting.Value;
        var helloSetting = config.GetSection("hello");
        string val = helloSetting.Value;

        //...
    }

示例 local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "APPINSIGHTS_INSTRUMENTATIONKEY": "123456..."
  }
}

示例 SomeOther.json

{
  "hello":  "world"
}