如何将 ILogger 依赖项注入到<T>配置服务中的服务 - .net 核心 2.0



我有以下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));

相关内容

  • 没有找到相关文章

最新更新