Search code examples
c#dependency-injectionasp.net-core-2.0.net-core-logging

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("[email protected]")
        };

        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?


Solution

  • Wouldn't this work?

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