在通用主机控制台应用程序中,我想使用IOptionsSnapshot <AppConfig>获取appsettings.json的值,但返回空白

时间:2019-06-29 04:43:33

标签: .net-core

我按照google中的示例制作了代码,但无法从appsettings.json获取值。

.net-core 2.2版

“ _ settings.TimerPeriod”值返回0,我不知道出了什么问题,期待您的帮助。

running results(click to show img)

Program.cs

static async Task Main(string[] args)
{
    var builder = new HostBuilder()
        .ConfigureLogging(factory =>
        {
            factory.AddNLog(new NLogProviderOptions
            {
                CaptureMessageTemplates = true,
                CaptureMessageProperties = true
            });
            NLog.LogManager.LoadConfiguration("nlog.config");
        })

        .ConfigureAppConfiguration((hostContext, config) =>
        {
            var env = hostContext.HostingEnvironment;
            config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                    config.AddEnvironmentVariables();
                    if (args != null)
            {
                config.AddCommandLine(args);
            }
        })

         .ConfigureServices((hostContext, services) =>
         {
             services.AddOptions();
             services.Configure<AppConfig>(hostContext.Configuration.GetSection("AppSettings"));
                     services.AddHostedService<TimerHostedService>();
         });

    await builder.RunConsoleAsync();
}

TimerHostedService.cs

    class TimerHostedService: BackgroundService
    {
        private Timer _timer;
        private ILogger _logger;
        private readonly AppConfig _settings;

        public TimerHostedService(ILogger<TimerHostedService> logger,IOptionsSnapshot<AppConfig> settings)
        {
            _logger = logger;
            _settings = settings.Value;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //Console.WriteLine($"Running, period:{_settings.TextOfStartToPrint}");
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(2));
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            _logger.LogInformation($"Timer is working in {DateTime.Now.ToString()},period:{_settings.TimerPeriod}");
        }
.....
}

appsettings.json

  "AppSettings": {
    "TimerPeriod": 2
  }

AppConfig.cs

public class AppConfig
{
    public int TimerPeriod { get; set; }
}

0 个答案:

没有答案