【二】、.net core 3.1 windows服务读取appsetting的步骤
1、在appsetting里添加节点
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "MQ": { "IP": "127.0.0.1", "Port": "61616", "UserName": "admin", "Password": "admin" } }
2、新建一个与之对应的类如下:
public class MQConfig { public string IP { get; set; } public string Port { get; set; } public string UserName { get; set; } public string Password { get; set; } }
3、修改Program里的CreateHostBuilder
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); services.Configure<MQConfig>(hostContext.Configuration.GetSection(key: "MQ")); }) .UseSerilog();
4、在worker里使用
public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private readonly MQConfig _mqConfig; public Worker(ILogger<Worker> logger, IOptions<MQConfig> settings) { _logger = logger; _mqConfig = settings.Value; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}" + "IP:{1},Port:{2}", DateTimeOffset.Now, _mqConfig.IP, _mqConfig.Port); await Task.Delay(1000, stoppingToken); } } }
4、结果如下:
示例代码地址:https://download.csdn.net/download/jiancaixing/20629212