• 【三】、.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、运行结果如下:

     示例代码地址:https://download.csdn.net/download/jiancaixing/20629212

  • 相关阅读:
    修改profile出错后的补救
    ubuntu安装jdk
    创业的36条军规
    Oracle中慎用Like等通配符
    根据配置文件名读取配置文件的工具类方法
    Spring ThreadPoolTaskExecutor队列满的异常处理
    redis使用方法
    在windows 2008 R2中SQl Server 2008中代理启动失败的一个原因总结
    select 中添加option的注意
    javascript 函数对象
  • 原文地址:https://www.cnblogs.com/wjx-blog/p/15075763.html
Copyright © 2020-2023  润新知