Net Core教程

.net core 3.1 windows服务依赖注入

本文主要是介绍.net core 3.1 windows服务依赖注入,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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) =>
                {
                    services.AddScoped<IServicesDoParse, ServicesDoParse>();
                    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服务依赖注入的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!