I have a Blazor project and use MailKit for sending emails.
I'd like to add Logger to the email service.
That is Startup.ConfigureServices
//...
services.AddSingleton<IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get<EmailConfiguration>());
//...
services.AddTransient<IEmailSender, EmailSender>();
//...
That is the EmailSender
service:
public class EmailSender : IEmailSender
{
private readonly IEmailConfiguration _emailConfiguration;
//private readonly ILogger<WHATModel> _logger; //<------------?
public EmailSender(IEmailConfiguration emailConfiguration)
{
_emailConfiguration = emailConfiguration;
}
public Task SendEmailAsync(string recipientEmail, string subject, string message)
{
//....
So, I can pass EmailConfiguration
to the service but how I can pass a ILogger
?
It requires some model
private readonly ILogger<WHATModel> _logger; //<------------?
What model should I pass?
The model is usually the type being injected into and acts as the category for identifying and grouping the logged information. ILogger<TCategoryName>
When an
ILogger
object is created, a category is specified for it. That category is included with each log message created by that instance ofILogger
. The category may be any string, but the convention is to use the class name, such as "TodoApi.Controllers.TodoController".
Reference Logging in .NET Core and ASP.NET Core: Log category
Include it in the constructor as an explicit dependency so that it can also be injected
public class EmailSender : IEmailSender {
private readonly IEmailConfiguration emailConfiguration;
private readonly ILogger<EmailSender> logger;
public EmailSender(IEmailConfiguration emailConfiguration, ILogger<EmailSender> logger) {
this.emailConfiguration = emailConfiguration;
this.logger = logger;
}
public Task SendEmailAsync(string recipientEmail, string subject, string message) {
//...
}
//...
}
The container will resolve and inject the dependency into the sender when resolving it.