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