gpt4 book ai didi

c# - 使用 IOption 的类的实例化

转载 作者:行者123 更新时间:2023-11-30 20:25:08 30 4
gpt4 key购买 nike

在 ASP.NET Core 2.1 中,我有一个使用 IOptions 接口(interface)发送电子邮件的类,如下所示:

public class Email
{
private readonly ManuelaIbiEmail manuelaIbiEmail;

public Email(IOptions<ManuelaIbiEmail> manuelaIbiEmail)
{
this.manuelaIbiEmail.Username = manuelaIbiEmail.Value.Username;
this.manuelaIbiEmail.Password = manuelaIbiEmail.Value.Password;
}

public async Task SendAsync(Contato contato)
{
var smtpClient = new SmtpClient
{
Host = "smtp.sendgrid.net",
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential(manuelaIbiEmail.Username, manuelaIbiEmail.Password)
};

using (var message = new MailMessage(contato.Email, "manuelaibi66@gmail.com")
{
Subject = "Email de Manuela Ibi Nutrição Integrada",
Body = $"{contato.Comentario}\nTelefone: {contato.Telefone}"
})
{
await smtpClient.SendMailAsync(message);
}
}
}

这个类必须在 Controller 中用类似“var whatever = new Email(???);”这样的行来实例化。以便可以调用 SendAsync 方法。

但这里的大局是我迷失在这个初始化过程中。我只是不知道在“Email(something)”中调用什么。

只是,提供更多信息以备不时之需:

系统应该从 Secrets 中读取用户名和密码,因此我在 Startup.cs 中有以下行:

services.Configure<ManuelaIbiEmail>(Configuration.GetSection("ManuelaIbiEmail"));

ManuelaIbiEmail 是一个非常简单的 POCO 类:

public class ManuelaIbiEmail
{
public string Username { get; set; }
public string Password { get; set; }
}

Controller 看起来像:

public class ContactController : Controller
{
private readonly ManuelaIbiEmail manuelaIbiEmail;

public IActionResult Contact()
{
return View(new Contato());
}

[HttpPost]
public async Task<IActionResult> ContactAsync(Contato contato)
{
var email = new Email();
email.SendAsync(contato);

return Ok();
}
}

如果有人能好心告诉我我缺少什么,我将不胜感激。

提前致谢

最佳答案

依赖注入(inject)的重点是不要那样做

您可以通过属性在方法中注入(inject)它:

public class ContactController : Controller
{
public IActionResult Contact()
{
return View(new Contato());
}

[HttpPost]
public async Task<IActionResult> ContactAsync(Contato contato, [FromServices]Email email)
{
email.SendAsync(contato);

return Ok();
}
}

或者通过构造函数注入(inject):

public class ContactController : Controller
{
private readonly EMail email;

public ContactController(Email email)
{
this.email = email;
}

public IActionResult Contact()
{
return View(new Contato());
}

[HttpPost]
public async Task<IActionResult> ContactAsync(Contato contato)
{
email.SendAsync(contato);

return Ok();
}
}

关于c# - 使用 IOption 的类的实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52166688/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com