Azure Function IWebJobsStartup 实现中的 ExecutionContext

ExecutionContext in Azure Function IWebJobsStartup implementation

如何在 Functions Startup class 中访问 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();

        }
    }
 }

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

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

This这个话题也很好讨论

    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"
}

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

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

var currentDirectory = executioncontextoptions.AppDirectory;

configuration = configurationBuilder.SetBasePath(currentDirectory)
          .AddJsonFile(ConfigFile, optional: false, reloadOnChange: true)    
          .Build();

当文档说 In a function app, default is %HOME%\site\wwwroot 这意味着如果你不指定这个环境变量,函数主机将使用 %HOME%\site\wwwroot .

public void Configure(IWebJobsBuilder builder)
    {
        var localRoot = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
        var azureRoot = $@"{Environment.GetEnvironmentVariable("HOME")}\site\wwwroot";

        var config = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
            .SetBasePath(localRoot ?? azureRoot )
            .AddJsonFile("appsettings.json", true)
            .AddJsonFile("local.settings.json", true)
            .AddEnvironmentVariables()
            .Build();            
    }