dependency-injectionblazorserilogmicrosoft.extensions.logging

MissingMethodException: No parameterless constructor defined for type


I have a Blazor app using .net core 5. I am trying to run a page to trigger an email send (EmailSample) which works fine until I try to add a constructor injection for logging errors. as soon as I add the constructor injection and rerun the page I get a No parameterless constructor defined for type error. Am I not using this correctly? How to fix so I don't get that error. I could get around this if I could figure out how to add logger as a service in Startup.cs/ConfigureServices/services.AddSingleton< ??? > and then just do the [Inject] in the EmailSample class but can't figure out how.

[Inject]
public ILogger _logger { get; set; }

The code that causes the error is... (Note: set up as a partial class, not in the .razor page @code{})

public partial class EmailSample
{
    private readonly ILogger<EmailSample> _logger;

    public EmailSample (ILogger<EmailSample> logger)
    {
        _logger = logger;
    }
[Inject]
    public IMailService _mailService { get; set; }
    
    public void SendEmail()
    {
        string emailTo = "test@test.com";
        string emailFrom = "noreply@test.com";
        string emailSubject = "This is a test email.";
        string emailType = "html";         
        string emailCc = string.Empty;

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.AppendLine("Hello" + " " + emailTo);
        sb.AppendLine("</br>");
        sb.AppendLine("This is a test of the email functionality");
        sb.AppendLine("</br>");
        sb.AppendLine("Best Regards,");
        sb.AppendLine("</br>");
        sb.AppendLine("Signature");
        string emailBody = sb.ToString();

        try
        {
            throw new Exception("This is an email sample exception test");
            //Task tSendEmail = _mailService.SendEmailAsync(emailTo, emailSubject, emailBody, emailFrom, emailCc, emailType);
            //if (tSendEmail.IsCompletedSuccessfully)
            //{
            //    _statusMessage = "The email has been sent successfully.";

            //}
            //else
            //{
            //    _statusMessage = "Failed to send email successfully.";
            //}
         
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "The email for { emailto } failed to send.", emailTo);
        }
    }
    public void OnGet()
    {

        _statusMessage = "";
    }
}

Solution

  • [Inject]
    private ILogger<EmailSample> logger {get; set;}
    

    Don't forget the namespace Microsoft.Extensions.Logging