我有以下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("info@domain.com")
};
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;
});
有没有办法获取logger实例并将其提供给邮件服务?
这不起作用吗?
services.AddTransient<IMailService>(provider =>
{
return new MailService(provider.GetRequiredService<ILogger<MailService>>(), new SmtpClient());
});
我想使用实现工厂创建此服务 因为我将从配置和供应中阅读SMTP设置 SMTP客户端
您不应该在实现工厂添加IMailService
,最好将SmtpClient
与实现工厂添加
services.AddTransient<IMailService, MailService>();
services.AddTransient(_ => new SmtpClient("127.0.0.1", 25));