У меня проблемы с чтением значений конфигурации из файла appSettings.json в webjob. Webjob использует следующие пакеты nuget:
![enter image description here](https://i.stack.imgur.com/syHFM.png)
В моем консольном приложении (webjob) у меня есть два файла настроек:
appsettings.development.json
appsettings.production.json
В методе Main веб-работа настраивается следующим образом:
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"));
}
}
Когда я запускаю свое веб-задание, я вижу, что журналы console.writeline никогда не выводят конфигурации, которые я пытаюсь прочитать в методе TimerTick.
Вопросы:
- Как добавить конфигурацию appSettings в метод TimerTick?
- У меня есть два файла 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"
}
}
}