我有一个使用 .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 = "[email protected]";
string emailFrom = "[email protected]";
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 = "";
}
}
[Inject]
private ILogger<EmailSample> logger {get; set;}
不要忘记命名空间 Microsoft.Extensions.Logging
我遇到了同样的问题,结果我没有将我的构造函数公开