我有一个使用 .net core 5 的 Blazor 应用程序。我正在尝试运行一个页面来触发电子邮件发送 (EmailSample),它可以正常工作,直到我尝试添加构造函数注入来记录错误。一旦我添加构造函数注入并重新运行页面,我就会得到一个No parameterless constructor defined for type
错误。我没有正确使用它吗?如何修复,这样我就不会收到该错误。如果我能弄清楚如何将记录器作为服务添加到其中Startup.cs/ConfigureServices/services.AddSingleton< ??? >
,然后只在 EmailSample 类中执行 [Inject] 但不知道如何解决,我就可以解决这个问题。
[Inject]
public ILogger _logger { get; set; }
导致错误的代码是......(注意:设置为部分类,而不是在 .razor 页面中@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 = "";
}
}