如何将 ILogger<T> 依赖项注入 ConfigureServices - .net core 2.0 中的服务

How to inject ILogger<T> dependency to a service in ConfigureServices - .net core 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 设置并提供 smtp 客户端,如下所示 Startup.cs:

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());
        });

I would like to create this service using an implementation factory because I will read the smtp settings from configuration and supply the smtp client

你不应该添加 IMailService with implementation factory, 你最好添加 SmtpClient with implementation factory

services.AddTransient<IMailService, MailService>();
services.AddTransient(_ => new SmtpClient("127.0.0.1", 25));