我正在 Blazor 应用程序 (.NET 5) 中设置 SendGrid 电子邮件发送器。
根据 SendGrid 文档和示例,他们正在编写一个签名为的方法static async Task
然后他们await
来自他们的 API 的响应。他们的示例代码立即运行Main()
并且不显示任何方法调用。
使用它作为静态方法是否违反了我应该如何使用依赖注入?我是否应该将此 EmailSender 类注册为具有依赖注入的服务,然后将其注入到需要发送电子邮件的组件中?
SendGrid 示例中的代码:
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
//Boilerplate code setting up email from/to/apiKey etc removed
var response = await client.SendEmailAsync(msg);
}
通过此设置,我可以将 Execute() 方法公开,然后直接将其作为静态方法调用。
制作如下内容是否更合适:
public class EmailService
{
public async Task SendEmail(string to, string subject, string message)
{
//Boilerplate code setting up email from/to/apiKey etc removed
var response = await client.SendEmailAsync(msg);
}
}
然后我可以通过 DI 注入并使用该服务,例如:
@inject EmailService emailService
@code {
//Calling line below in the appropriate spot
await emailService.SendEmail(to, subject, message);
}
.NET Core 中的通用实现:
启动.cs
using SendGrid.Extensions.DependencyInjection; // nuget package: https://www.nuget.org/packages/SendGrid.Extensions.DependencyInjection
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// sendgrid
services.AddSendGrid(options =>
{
options.ApiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
});
}
}
电子邮件控制器.cs
using SendGrid; // nuget package
public class EmailController : ControllerBase
{
private ISendGridClient _sendGridClient;
public EmailController(ISendGridClient sendGridClient)
{
_sendGridClient = sendGridClient;
}
public IActionResult SendEmail(Email email)
{
var emailManager = new EmailManager(_sendGridClient);
return emailManager.SendEmail(email);
}
}
电子邮件管理器.cs
using SendGrid;
public class EmailManager
{
private ISendGridClient _sendGridClient;
public EmailManager(ISendGridClient sendGridClient)
{
_sendGridClient = sendGridClient;
}
public bool SendEmail(Email email)
{
...
var response = await _sendGridClient.SendEmailAsync(msg);
...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)