简体   繁体   English

使用 Autofac 在构造函数中注入带有 IOptions 的类

[英]Injecting a class with IOptions in the constructor with Autofac

I am using Autofac as a container that I am using in another console app that uses the same objects as my main web app, and am trying to inject a class that has IOptions inside his constructor, here's how it looks like:我正在使用 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;
        }
    }
}

as you can see the constructor is getting some settings from the injected stmpSettings, any idea to how I could inject it with the autofac container?如您所见,构造函数正在从注入的 stmpSettings 中获取一些设置,对如何将其注入 autofac 容器有任何想法吗?

so far I have到目前为止我有

builder.RegisterType<Mailer>().As<IMailer>();

but I need to include the things that the constructor injects as well.但我还需要包括构造函数注入的东西。 having a real hard time understanding to how to do it, any help would be appreciated!很难理解如何做到这一点,任何帮助将不胜感激!

With Populate method you can register services to Autofac that registered by .Net Core services.使用Populate方法,您可以向Autofac注册由.Net Core服务注册的服务。

Create a method like this创建一个这样的方法

public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services)
{
    var containerBuilder = new ContainerBuilder();
    containerBuilder.Populate(services);
    var container = containerBuilder.Build();
    return new AutofacServiceProvider(container);
}

Change the return type of ConfigureServices method to IServiceProviderConfigureServices方法的返回类型更改为IServiceProvider

public IServiceProvider ConfigureServices(IServiceCollection services)
{
      //register services
    return services.BuildAutofacServiceProvider();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM