我有一个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" } }