如何通过依赖注入将.NET Core Worker Service日志对象注入.NET Standard类库
标准依赖注入注入日志的改造方案
问题根因
你当前手动给SendRemainder的_logger属性赋值的方式,本质是因为SendRemainder的注册逻辑没有接入DI的依赖解析链路,日志作为内置服务没有被自动注入。
具体改造步骤
1. 改造类库中SendRemainder类
把原本需要外部赋值的公共_logger改为构造函数注入的私有字段,类的其他业务逻辑不需要改动:
public class SendRemainder : ISendRemainder<RemainInfo> { // 改为私有构造注入的日志实例,移除原有的公共可赋值的_logger属性 private readonly ILogger<SendRemainder> _logger; private readonly string _applicationUrl; private readonly string _contentRootPath; private readonly string _smtpHost; // 构造函数新增日志参数,原有业务参数保留 public SendRemainder( ILogger<SendRemainder> logger, string applicationUrl, string contentRootPath, string smtpHost) { _logger = logger; _applicationUrl = applicationUrl; _contentRootPath = contentRootPath; _smtpHost = smtpHost; } // 原有SendDSRRemainderEmails、SendDSMRemainderEmails方法无需修改,直接使用私有_logger即可 }
2. 调整Worker项目的DI注册逻辑
修改SendRemainder的注册工厂,从DI容器中自动获取已注册的日志实例,不再手动传递:
// 替换原来的SendRemainder注册逻辑 services.AddSingleton<ISendRemainder<RemainInfo>, SendRemainder>(serviceProvider => { // 从DI容器中获取内置的ILogger<SendRemainder>实例,Host.CreateDefaultBuilder已默认注册该服务 var logger = serviceProvider.GetRequiredService<ILogger<SendRemainder>>(); // 原有业务参数从配置、环境中读取 var appUrl = configuration.GetValue<string>("AppURL"); var contentRootPath = hostContext.HostingEnvironment.ContentRootPath; var smtpHost = configuration.GetValue<string>("SMTPHost"); return new SendRemainder(logger, appUrl, contentRootPath, smtpHost); });
3. 清理Worker中的手动赋值代码
SendRemainder的日志已经由DI自动注入,直接删除Worker类中手动给日志赋值的行即可:
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); List<RemainInfo> ls = _getRemainInfo.GetAppsToRemains("CA_Remain_Applications"); // 直接删除原手动赋值行:this._sendRemain._logger = _logger; _sendRemain.SendDSRRemainderEmails(ls); _sendRemain.SendDSMRemainderEmails(ls); await Task.Delay(360000, stoppingToken); } }
通用扩展
类库中其他需要使用日志的类(如GetRemainderInfo、AdoSqlServerAccesss),都可以直接在构造函数中注入ILogger<对应的类名>,不需要额外注册,DI容器会自动解析对应的日志实例。
补充:默认的
Host.CreateDefaultBuilder已经完成了日志服务的注册,不需要手动添加services.AddLogging()相关逻辑。
内容的提问来源于stack exchange,提问作者wpp
相关产品推荐
相关产品推荐

