我有以下MailService
:
public class MailService : IMailService
{
private readonly ILogger<MailService> _logger;
private readonly SmtpClient _client;
public MailService(ILogger<MailService> logger, SmtpClient client)
{
_logger = logger;
_client = client;
}
public async Task Send(string to, string subject, string body)
{
var message = new MailMessage
{
Subject = subject,
Body = body,
IsBodyHtml = true,
From = new MailAddress("[email protected]")
};
message.To.Add(to);
using (_client)
{
_logger.LogTrace($"Sending email from {message.From.Address} to {to}. Subject: {subject}");
await _client.SendMailAsync(message);
}
}
}
我想使用实现工厂来创建此服务,因为我将从配置中读取smtp设置,并像
Startup.cs
中所示的那样提供smtp客户端:services.AddTransient<IMailService>(provider =>
{
var mailService = new MailService(***LOGGER INSTANCE HERE***, new SmtpClient("127.0.0.1", 25));
return mailService;
});
有没有办法获取记录器实例并将其提供给邮件服务?
最佳答案
这行不行吗?
services.AddTransient<IMailService>(provider =>
{
return new MailService(provider.GetRequiredService<ILogger<MailService>>(), new SmtpClient());
});