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

前端之家收集整理的这篇文章主要介绍了配置 – ASP.NET Core Expose配置到DI注入服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个ASP.NET核心WebAPI项目,我正在尝试添加配置到我的IEmailServic,我通过DI注入这样:
services.AddTransient<IEmailSender,AuthMessageSender>();

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

解决方法

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

>创建您的EmailSettings强类型配置类:

public class EmailSettings  
{
    public string HostName { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

>更新您的appsettings.json以包含映射到您的EmailSettings配置类的配置部分:

{
  "Logging": {
    "IncludeScopes": false,"LogLevel": {
      "Default": "Debug","System": "Information","Microsoft": "Information"
    }
  },"EmailSettings": {
    "HostName": "myhost.com","Username": "me","Password": "mysupersecretpassword",}
}

>在Startup类的ConfigureServices调用中,将appsettings.json绑定到您的config类

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

>在AuthMessageSender类中,注入IOptions实例< EmailSettings>进入构造函数

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"
  }
}

猜你在找的.NET Core相关文章