我有以下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设置并提供smtp客户端,如Startup.cs
中的以下内容:
services.AddTransient<IMailService>(provider =>
{
var mailService = new MailService(***LOGGER INSTANCE HERE***, new SmtpClient("127.0.0.1", 25));
return mailService;
});
有没有办法获取记录器实例并将其提供给邮件服务?
答案 0 :(得分:2)
我想使用实现工厂创建此服务 因为我会从配置和供应中读取smtp设置 smtp客户端
您不应该在实施工厂中添加IMailService
,最好在实施工厂中添加SmtpClient
services.AddTransient<IMailService, MailService>();
services.AddTransient(_ => new SmtpClient("127.0.0.1", 25));
答案 1 :(得分:1)
这不会起作用吗?
services.AddTransient<IMailService>(provider =>
{
return new MailService(provider.GetRequiredService<ILogger<MailService>>(), new SmtpClient());
});