【发布时间】:2021-12-17 15:48:16
【问题描述】:
我正在 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);
}
【问题讨论】:
-
我不明白使用 nuget 包来发送邮件,而框架可以做到这一点。
-
@LeandroBardelli 知道有内置的东西可以做到这一点,但决定使用 SendGrid 来提供他们提供的其他功能。
-
@aterbo 谢谢,我现在明白了!我只是从我看到的代码中提出意见。对不起我的建议。
-
无需道歉,感谢您的意见
-
您似乎在正确的路线上。然而,问题:
var response = await client.SendEmailAsync(msg);中的client是什么?它必须在 SendGrid 示例中的某处定义。
标签: c# dependency-injection blazor sendgrid blazor-server-side