【用.NET5写Windows服务】三、读写配置文件

读写配置文件appsettings.json是编码中经常用到的功能,所以放到前面来写,为后面的开发做好铺垫。

此篇,我们将通过设置托管服务的默认轮询时间,来学习读写配置文件appsettings.json

appsettings.json中添加配置节

{
    
    
  ...
  "HostedService": {
    
    
    "WorkerInterval": 60000 //++托管任务轮询时间
  } 
}

选项模式

官方推荐用选项模式来读取配置。所谓选项其实就是一个非抽象类。
详见官方文档

新建一个HostedServiceOptions.cs文件。注意:此类的结构须与appsettings.json中的json结构保持一致。

namespace dotnet5_winservice_demo.Options
{
    
    
    public class HostedServiceOptions
    {
    
    
        public const string HostedService = "HostedService";

        public string WorkerInterval {
    
     get; set; }
    }
}

读取选项的值

读取HostedServiceOptions配置值,并设置成托管任务轮询时间。

public class Worker : BackgroundService
{
    
    
    private readonly ILogger<Worker> _logger;
    private readonly IConfiguration _configuration;

    public HostedServiceOptions HostedServiceOptions {
    
     get; private set; }

    public Worker(ILogger<Worker> logger, IConfiguration configuration)
    {
    
    
        _logger = logger;
        _configuration = configuration; //++依赖注入IConfiguration
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
    
    
        HostedServiceOptions = _configuration.GetSection(HostedServiceOptions.HostedService).Get<HostedServiceOptions>(); //++绑定并返回指定的类型

        while (!stoppingToken.IsCancellationRequested)
        {
    
    
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(HostedServiceOptions.WorkerInterval, stoppingToken); //++设置托管任务轮询时间
        }
    }
}

选项模式的替代方法:绑定并依赖注入服务容器

使用委托来配置选项

向服务容器添加IConfigureOptions<TOptions>服务。 它使用委托来配置HostedServiceOptions的值。
详见官方文档

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseWindowsService() //支持Windows服务
        .UseSystemd() //支持Linux守护进程
        .ConfigureLogging((hostingContext, logging) =>
        {
    
    
            // The ILoggingBuilder minimum level determines the
            // the lowest possible level for logging. The log4net
            // level then sets the level that we actually log at.
            logging.AddLog4Net(); //添加log4net
            logging.SetMinimumLevel(LogLevel.Debug); //设置最低级别为Debug
        })
        .ConfigureServices((hostContext, services) =>
        {
    
    
            services.Configure<HostedServiceOptions>(options =>
            {
    
    
                options.WorkerInterval = 1000 * 60; //++设置托管任务默认轮询时间为1分钟。
            });
            services.AddHostedService<Worker>(); //每添加一个托管服务类,都需要在此处添加配置。
        });
    }

读取选项的值

读取HostedServiceOptions配置值,并设置成托管任务轮询时间。

public class Worker : BackgroundService
{
    
    
    private readonly ILogger<Worker> _logger;
    private readonly IOptions<HostedServiceOptions> _hostedServiceOptions;

    public Worker(ILogger<Worker> logger, IOptions<HostedServiceOptions> hostedServiceOptions)
    {
    
    
        _logger = logger;
        _hostedServiceOptions = hostedServiceOptions; //++依赖注入IOptions
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
    
    
        while (!stoppingToken.IsCancellationRequested)
        {
    
    
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(_hostedServiceOptions.Value.WorkerInterval, stoppingToken); //++设置托管任务轮询时间
        }
    }
}

猜你喜欢

转载自blog.csdn.net/danding_ge/article/details/112017248
今日推荐