我有一个Blazor项目,并使用MailKit发送电子邮件。
我想将记录器添加到电子邮件服务中。
这是Startup.ConfigureServices
//...
services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
//...
services.AddTransient<IEmailSender, EmailSender>();
//...
这是EmailSender
服务:
public class EmailSender : IEmailSender
{
private readonly IEmailConfiguration _emailConfiguration;
//private readonly ILogger<WHATModel> _logger; //<------------?
public EmailSender(IEmailConfiguration emailConfiguration)
{
_emailConfiguration = emailConfiguration;
}
public Task SendEmailAsync(string recipientEmail, string subject, string message)
{
//....
那么,我可以将EmailConfiguration
传递给服务,但是我如何传递ILogger
?
它需要一些模型
private readonly ILogger<WHATModel> _logger; //<------------?
我应该通过什么模型?
模型通常是注入到的类型,并充当标识和分组记录信息的类别。ILogger<TCategoryName>
创建
ILogger
对象时,将为其指定类别。该类别包含在该ILogger
实例创建的每条日志消息中。类别可以是任何字符串,但约定是使用类名,例如"TodoApi.Controllers.TodoController"。
.NET Core 和 ASP.NET Core 中的引用日志记录:日志类别
将其作为显式依赖项包含在构造函数中,以便也可以注入它
public class EmailSender : IEmailSender {
private readonly IEmailConfiguration emailConfiguration;
private readonly ILogger<EmailSender> logger;
public EmailSender(IEmailConfiguration emailConfiguration, ILogger<EmailSender> logger) {
this.emailConfiguration = emailConfiguration;
this.logger = logger;
}
public Task SendEmailAsync(string recipientEmail, string subject, string message) {
//...
}
//...
}
容器将在解析依赖项时将其解析并注入到发送方中。