.net core 3.1 windows服务依赖注入教程

2021-07-29由程序员日记发表于系统教程 浏览21次

1、建立一个接口

    public interface IServicesDoParse
    {
        void Do();
    }

2、做一个接口的实现

    public class ServicesDoParse : IServicesDoParse
    {
        private readonly ILogger<IServicesDoParse> _logger;
        private readonly MQConfig _mqConfig;

        public ServicesDoParse(ILogger<ServicesDoParse> logger, IOptions<MQConfig> settings)
        {
            _logger = logger;
            _mqConfig = settings.Value;
        }
        public void Do()
        {
            _logger.LogInformation("ServicesDoParse运行成功,在注入的服务里读取IP:", _mqConfig.IP);
        }
    }

3、在Program的CreateHostBuilder里添加

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureServices((hostContext, services) =>
                {
                    <strong>services.AddScoped</strong><strong><IServicesDoParse, ServicesDoParse></strong><strong>();</strong>
                    services.AddHostedService<Worker>();
                    services.Configure<MQConfig>(hostContext.Configuration.GetSection(key: "MQ"));
                })
            .UseSerilog();

4、实际使用

    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;
        private readonly MQConfig _mqConfig;
        private readonly IServiceProvider _serviceProvider;

        public Worker(ILogger<Worker> logger, IOptions<MQConfig> settings, IServiceProvider serviceProvider)
        {
            _logger = logger;
            _mqConfig = settings.Value;
            _serviceProvider = serviceProvider;
        }

        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);

                using (var scope = _serviceProvider.CreateScope())
                {
                    var service = scope.ServiceProvider.GetRequiredService<IServicesDoParse>();
                    service.Do();
                }

                await Task.Delay(1000, stoppingToken);
            }
        }
    }

5、运行结果如下:

.net core 3.1 windows服务依赖注入教程