简体   繁体   中英

How to inject ILogger<T> dependency to a service in ConfigureServices - .net core 2.0

I have the following 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);
        }
    }

}

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 like the following in Startup.cs :

services.AddTransient<IMailService>(provider =>
{
    var mailService = new MailService(***LOGGER INSTANCE HERE***, new SmtpClient("127.0.0.1", 25));
    return mailService;
});

Is there a way to grab a logger instance and supply that to the mail service?

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

You should not add IMailService with implementation factory, It's better that you add SmtpClient with implementation factory

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

Wouldn't this work?

services.AddTransient<IMailService>(provider =>

        {
            return new MailService(provider.GetRequiredService<ILogger<MailService>>(), new SmtpClient());
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM