ASP.NET Core Expose配置到DI注入服务

时间:2016-06-29 19:23:22

标签: configuration asp.net-core

我有一个ASP.NET Core WebAPI项目,我正在尝试将配置添加到我通过DI注入的IEmailService中:

services.AddTransient<IEmailSender, AuthMessageSender>();

AuthMessageSender的实例如何在配置文件中进行设置?

2 个答案:

答案 0 :(得分:25)

您应该使用强类型配置的options模式:

  1. 创建EmailSettings强类型配置类:
  2. public class EmailSettings  
    {
        public string HostName { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
    
    1. 更新 appsettings.json 以包含映射到EmailSettings配置类的配置部分:
    2. {
        "Logging": {
          "IncludeScopes": false,
          "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
          }
        },
        "EmailSettings": {
          "HostName": "myhost.com",
          "Username": "me",
          "Password": "mysupersecretpassword",
        }
      }
      
      1. ConfigureServices类的Startup调用中,将 appsettings.json 绑定到您的配置类
      2. public void ConfigureServices(IServiceCollection services)  
        {
            services.Configure<MySettings>(
                  options => Configuration.GetSection("EmailSettings").Bind(options));
        }
        
        1. AuthMessageSender类中,将IOptions<EmailSettings>的实例注入构造函数
        2. public class AuthMessageSender
          {
              private readonly EmailSettings _settings;
              public AuthMessageSender(IOptions<EmailSettings> emailSettings)
              {
                 _settings = emailSettings.Value;
                // _settings.HostName == "myhost.com";
              }
          }
          

          请注意,在步骤3中,您还可以使用

          public void ConfigureServices(IServiceCollection services)  
          {
              services.Configure<MySettings>(Configuration.GetSection("EmailSettings"));
          }
          

          如果您在 project.json 中添加对 Microsoft.Extensions.Options.ConfigurationExtensions 的引用:

          {
            "dependencies": {
               "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0"
            }
          }
          

答案 1 :(得分:1)

推荐的模式是读取您需要的特定配置条目at startup并将它们存储在DI中的选项实例中,并注入特定选项类型into your other components