ASP.NET Core Expose Config to DI Injected Service

ぃ、小莉子 提交于 2021-01-26 19:22:11

问题


I have a ASP.NET Core WebAPI project and I am trying to add configuration to my IEmailServicethat I am injecting through DI like this:

services.AddTransient<IEmailSender, AuthMessageSender>();

How can instances of AuthMessageSender get to settings in the config file?


回答1:


You should use the options pattern with strongly typed configuration:

  1. Create your EmailSettings strongly typed configuration class:
public class EmailSettings  
{
    public string HostName { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}
  1. Update your appsettings.json to include a configuration section that maps to your EmailSettings configuration class:
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "EmailSettings": {
    "HostName": "myhost.com",
    "Username": "me",
    "Password": "mysupersecretpassword",
  }
}
  1. In the ConfigureServices call of your Startup class, bind appsettings.json to your config class
public void ConfigureServices(IServiceCollection services)  
{
    services.Configure<MySettings>(
          options => Configuration.GetSection("EmailSettings").Bind(options));
}
  1. In your AuthMessageSender class, inject an instance of IOptions<EmailSettings> into the constructor
public class AuthMessageSender
{
    private readonly EmailSettings _settings;
    public AuthMessageSender(IOptions<EmailSettings> emailSettings)
    {
       _settings = emailSettings.Value;
      // _settings.HostName == "myhost.com";
    }
}

Note that in step 3, you can also use

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

If you add a reference to Microsoft.Extensions.Options.ConfigurationExtensions in project.json:

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



回答2:


The recommended pattern is to read the specific config entries you need at startup and store them in an Options instance in DI, and inject that specific options type into your other components.



来源:https://stackoverflow.com/questions/38108400/asp-net-core-expose-config-to-di-injected-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!