问题描述
我已经在.Net Core中创建了一个Worker Service,并在.NET标准中创建了一个类库。
我的工人中的DI看起来像这样:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext,services) =>
{
IConfiguration configuration = hostContext.Configuration;
services.AddSingleton<IAdosqlServerAccesss,AdosqlServerAccesss>(serviceProvider =>
{
return new AdosqlServerAccesss(configuration.GetConnectionString("DefaultConnection"));
});
services.AddSingleton<IsqlServerDataExtract,sqlServerDataExtract>();
services.AddSingleton<IGetRemainderInfo<RemainInfo>,GetRemainderInfo>();
services.AddSingleton<ISendRemainder<RemainInfo>,SendRemainder>(serviceProvider =>
{
return new SendRemainder(configuration.GetValue<string>("AppURL"),hostContext.HostingEnvironment.ContentRootPath,configuration.GetValue<string>("SMTPHost"));
});
services.AddHostedService<Worker>();
});
像这样:
private readonly ILogger<Worker> _logger;
private readonly IGetRemainderInfo<RemainInfo> _getRemainInfo;
private readonly ISendRemainder<RemainInfo> _sendRemain;
public Worker(ILogger<Worker> logger,IGetRemainderInfo<RemainInfo> getRemainInfo,ISendRemainder<RemainInfo> sendRemain)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_getRemainInfo = getRemainInfo ?? throw new ArgumentNullException(nameof(getRemainInfo));
_sendRemain = sendRemain ?? throw new ArgumentNullException(nameof(sendRemain));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.Loginformation("Worker running at: {time}",DateTimeOffset.Now);
List<RemainInfo> ls = this._getRemainInfo.GetAppsToRemains("CA_Remain_Applications");
this._sendRemain._logger = _logger;
this._sendRemain.SendDSRRemainderEmails(ls);
this._sendRemain.SendDSMRemainderEmails(ls);
await Task.Delay(360000,stoppingToken);
}
}
worker的所有功能都在类库中的类内部。 然后,在worker中,我从类库中调用此函数,并且需要在此函数中使用记录器,但是我不确定如何通过DI将记录器实例从worker项目传递到类库:
public void SendDSRRemainderEmails(List<RemainInfo> lst)
{
try
{
_logger?.Loginformation("DoSometing INFO message");
var onlyDsr = from info in lst
where info.DSR_EMAIL != ""
group info by info.Number;
MailModel mailinfo = new MailModel();
//iterate each group
foreach (var dsrGroup in onlyDsr)
{
string Apps = "";
foreach (var s in dsrGroup) //Each group has a inner collection
{
Apps += s.CORPORATION_NAME + "<br/>";
}
String body = Utils.GetApplicationTemplateBody(_pathproject + Utils.RemainDSRTemplatePath);
List<string> To = new List<string>();
To.Add(dsrGroup.First().DSR_EMAIL);
body = body.Replace("{SendSubject}","Remainder of the Applications that you have pending of action");
body = body.Replace("{DSRNAME}",dsrGroup.First().Name + ",yu have these applications pending of an action by you or your client:");
body = body.Replace("{listofAPPLICATIONS}",Apps);
body = body.Replace("{ApplicationURL}",_applicationurl);
mailinfo.To = To; // From = ConfigurationManager.AppSettings["SendNotificationsFromMailID"]
mailinfo.Subject = Utils.RemainSubject;
mailinfo.Body = body;
Utils.SendMail(mailinfo,_smtpHost);
}
}
catch(Exception ex)
{
_logger?.LogError("ERROR in SendDSRRemainderEmails: " + ex.Message + ( ex.InnerException != null ? ex.InnerException.Message : "") );
// Test logs at each level
/* _logger?.LogTrace("DoSometing TRACE message");
_logger?.LogDebug("DoSometing DEBUG message");
_logger?.Loginformation("DoSometing INFO message");
_logger?.LogWarning("DoSometing WARN message");
_logger?.LogCritical("DoSometing CRITICAL message"); */
}
}
解决方法
我已经解决了我的问题,这里的解决方案非常简单:
在工人方面:
this
在类库方面:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext,services) =>
{
IConfiguration configuration = hostContext.Configuration;
services.AddSingleton<IAdoSqlServerAccesss,AdoSqlServerAccesss>(serviceProvider =>
{
return new AdoSqlServerAccesss(configuration.GetConnectionString("DefaultConnection"));
});
services.AddSingleton<ISqlServerDataExtract,SqlServerDataExtract>();
services.AddSingleton<IGetRemainderInfo<RemainInfo>,GetRemainderInfo>();
services.AddSingleton<ISendRemainder<RemainInfo,MailModel>,SendRemainder>(serviceProvider =>
{
var logger = serviceProvider.GetRequiredService<ILogger<SendRemainder>>();
return new SendRemainder(configuration.GetValue<string>("AppURL"),hostContext.HostingEnvironment.ContentRootPath,configuration.GetValue<string>("SMTPHost"),configuration.GetValue<string>("From"),logger);
});
services.AddHostedService<Worker>();
});
}
解决方案非常简单,在工作端,我只是在类库的类创建过程中添加了以下代码行:
private readonly ILogger _logger;
public SendRemainder(string creditappurl,string pathproject,string smtpHost,string from,ILogger<SendRemainder> logger)
{
this._applicationurl = creditappurl;
this._pathproject = pathproject;
this._smtpHost = smtpHost;
this._From = from;
_logger = logger;
}
然后我将这个变量从类库传递给类的构造函数:
var logger = serviceProvider.GetRequiredService<ILogger<SendRemainder>>();<br>