Azure Function IWebJobsStartup 实现中的 ExecutionContext [英] ExecutionContext in Azure Function IWebJobsStartup implementation

查看:8
本文介绍了Azure Function IWebJobsStartup 实现中的 ExecutionContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

[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 Function 尚未处理实际的函数调用.但你也不需要它 - local.settings.json 会自动解析到环境变量中.

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.

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

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;

        //...
    }

local.settings.json 示例:

Example local.settings.json:

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

例如 SomeOther.json

Example SomeOther.json

{
  "hello":  "world"
}

这篇关于Azure Function IWebJobsStartup 实现中的 ExecutionContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆