Azure函数IWebJobsStartup实现中的ExecutionContext

Som*_*dda 7 azure azure-functions azure-functions-runtime azure-functions-core-tools

如何获取对函数启动类中的ExecutionContext.FunctionAppDirectory的访问权限,以便我可以正确设置我的Configuration。请查看以下启动代码:

[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();

        }
    }
 }
Run Code Online (Sandbox Code Playgroud)

小智 12

使用下面的代码,它对我有用。

var executioncontextoptions = builder.Services.BuildServiceProvider()
         .GetService<IOptions<ExecutionContextOptions>>().Value;

var currentDirectory = executioncontextoptions.AppDirectory;

configuration = configurationBuilder.SetBasePath(currentDirectory)
          .AddJsonFile(ConfigFile, optional: false, reloadOnChange: true)    
          .Build();
Run Code Online (Sandbox Code Playgroud)


Ale*_*AIT 10

您没有,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;

        //...
    }
Run Code Online (Sandbox Code Playgroud)

示例local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "APPINSIGHTS_INSTRUMENTATIONKEY": "123456..."
  }
}
Run Code Online (Sandbox Code Playgroud)

示例SomeOther.json

{
  "hello":  "world"
}
Run Code Online (Sandbox Code Playgroud)