【发布时间】:2020-10-19 03:53:49
【问题描述】:
我正在使用 Autofac 作为我在另一个控制台应用程序中使用的容器,该控制台应用程序使用与我的主 Web 应用程序相同的对象,并尝试在其构造函数中注入一个具有 IOptions 的类,它的外观如下:
public class Mailer : IMailer
{
private readonly StmpSettings _stmpSettings;
public Mailer(IOptions<StmpSettings> stmpSettings)
{
_stmpSettings = stmpSettings.Value;
}
public async Task SendEmailAsync(string email, string subject, string body)
{
try
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_stmpSettings.SenderName, _stmpSettings.SenderEmail));
message.To.Add(new MailboxAddress(email));
message.Subject = subject;
message.Body = new TextPart("html")
{
Text = body
};
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
//I am using my own certificate for https. so when trying to connect to google smtp it cannot authenticate the certificate. I used this temp workaround: SecureSocketOptions.Auto.
//It means that the mail wont be encrypted.
//https://github.com/jstedfast/MailKit/blob/master/FAQ.md#SslHandshakeExceptionhttps://support.google.com/mail/?p=InvalidSecondFactor look for more secure solutions.
await client.ConnectAsync(_stmpSettings.Server, _stmpSettings.Port, SecureSocketOptions.Auto);
await client.AuthenticateAsync(_stmpSettings.Username, _stmpSettings.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
}
catch (Exception e)
{
throw e;
}
}
}
正如您所见,构造函数正在从注入的 stmpSettings 中获取一些设置,知道如何将其注入 autofac 容器吗?
目前为止
builder.RegisterType<Mailer>().As<IMailer>();
但我还需要包含构造函数注入的东西。 很难理解如何做到这一点,任何帮助将不胜感激!
【问题讨论】:
-
您可以参考autofac guide for ASP .NET Core并使用适当的注册。也许,您还应该手动注册
IOptions<StmpSettings> -
是的,我知道这是我应该做的,但我无法手动注册 IOptions
标签: c# asp.net-core-mvc autofac