umutesen
umutesen

Reputation: 2640

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?

Upvotes: 2

Views: 4482

Answers (2)

Kahbazi
Kahbazi

Reputation: 14995

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

Upvotes: 2

Umar Karimabadi
Umar Karimabadi

Reputation: 980

Wouldn't this work?

services.AddTransient<IMailService>(provider =>

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

Upvotes: 6

Related Questions