gpt4 book ai didi

.net-core - azure webjob : Read appSettings. json 并将配置注入(inject) TimerTrigger

转载 作者:行者123 更新时间:2023-12-04 13:02:05 28 4
gpt4 key购买 nike

我无法从 webjob 中的 appSettings.json 文件读取配置值。 webjob 使用以下 nuget 包:

enter image description here

我的控制台应用程序(webjob)中有两个设置文件:
appsettings.development.json
appsettings.production.json

在Main方法中,webjob的配置如下:

 static void Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureWebJobs(webJobConfiguration =>
{
webJobConfiguration.AddTimers();
webJobConfiguration.AddAzureStorageCoreServices();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
Console.WriteLine("hostingContext.HostingEnvironment: " + env.EnvironmentName);
config.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables().Build();
})
.ConfigureServices((context, serviceCollection) =>
{
serviceCollection.AddSingleton<IConfiguration>(context.Configuration);
serviceCollection.AddTransient<SayHelloWebJob>(job => new SayHelloWebJob(context.Configuration));
})
.Build();

builder.Run();
}

SayHelloWebJob 的代码如下:
public class SayHelloWebJob
{
static IConfiguration _configuration;
public SayHelloWebJob(IConfiguration config)
{
_configuration = config;
Console.WriteLine("Initialized SayHelloWebJob");
}

[Singleton]
public static void TimerTick([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer)
{
Console.WriteLine($"From SayHelloWebJob: Hello at {DateTime.UtcNow.ToString()}");
var test = _configuration.GetSection("WebJobConfiguration:message").Value;
Console.WriteLine("Configuration access: message: " + test);
Console.WriteLine("Configuration access: " + _configuration.GetSection("WebJobConfiguration:api").Value);
Console.WriteLine("configuration object: "+ _configuration.GetConnectionString("AzureWebJobsStorage"));

}
}

当我运行我的 webjob 时,我看到 console.writeline 日志从不输出我试图在 TimerTick 方法中读取的配置。

问题:
  • 如何在 TimerTick 方法中注入(inject) appSettings 配置?
  • 我有两个 appSettings 文件 - 用于开发和生产。如何确保在生产过程中加载了正确的文件?

  • 下面的示例 appSettings.development.json 文件:
    {
    "connectionStrings": {
    "AzureWebJobsStorage": stringhere",
    "AzureWebJobsDashboard": "stringhere"
    },
    "WebJobConfiguration": {
    "message": "I'm running locally!",
    "pfuWebApiUrl": "API link here",
    "api": "api here",
    "ApplicationInsights": {
    "InstrumentationKey": "key here"
    }
    }

    }

    最佳答案

    我的偏好是像您一样检查所有环境配置,并且绝对可以在运行时根据环境加载正确的文件。

    首先在 Visual Studio 的“属性” Pane 中将您的配置文件设置为“复制到较新的输出目录”,或将其添加到您的 csproj:

        <None Update="base.settings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
    <None Update="prod.settings.json">
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>

    现在您只需要在运行时加载正确的配置。

            private static IConfigurationRoot GetConfiguration(string basePath)
    {
    string filename = Constants.IsAzureEnvironment ? "prod.settings.json" : "dev.settings.json";

    IConfigurationBuilder configBuilder = new ConfigurationBuilder()
    .SetBasePath(basePath)
    .AddJsonFile("base.settings.json")
    .AddJsonFile(filename);

    return configBuilder.Build();
    }

    我从 azure 函数的 executionContext 参数中获取 basePath

            [FunctionName("Function1")]
    public static async Task<IActionResult> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext context)
    {
    // context.FunctionAppDirectory
    return new OkResult();
    }

    关于.net-core - azure webjob : Read appSettings. json 并将配置注入(inject) TimerTrigger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54155903/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com