ExecutionContext in Azure Function IWebJobsStartup implementation

后端 未结 2 1901
一生所求
一生所求 2021-02-08 04:54

How to get access to the ExecutionContext.FunctionAppDirectory in Functions Startup class so I can setup my Configuration correct. Please see the following Startup code:

相关标签:
2条回答
  • 2021-02-08 05:18

    Use below code ,It worked for me.

    var executioncontextoptions = builder.Services.BuildServiceProvider()
             .GetService<IOptions<ExecutionContextOptions>>().Value;
    
    var currentDirectory = executioncontextoptions.AppDirectory;
    
    configuration = configurationBuilder.SetBasePath(currentDirectory)
              .AddJsonFile(ConfigFile, optional: false, reloadOnChange: true)    
              .Build();
    
    0 讨论(0)
  • 2021-02-08 05:32

    You don't have the ExecutionContext since your Azure Function is not yet processing an actual function call. But you don't need it either - the local.settings.json is automatically parsed into the environment variables.

    If you really need the directory, you can use %HOME%/site/wwwroot in Azure, and AzureWebJobsScriptRoot when running locally. This is the equivalent of FunctionAppDirectory.

    This is also a good discussion about this topic.

        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;
    
            //...
        }
    

    Example local.settings.json:

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

    Example SomeOther.json

    {
      "hello":  "world"
    }
    
    0 讨论(0)
提交回复
热议问题