【发布时间】:2021-12-31 13:38:39
【问题描述】:
我有一个使用 .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 = "";
}
}
【问题讨论】:
-
我会注意到在 cshtml.cs razor pages 中实现构造函数注入时我没有同样的问题。
标签: dependency-injection blazor serilog microsoft.extensions.logging