.net core 3.1 windows服務依賴注入
阿新 • • 發佈:2021-07-29
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、執行結果如下: