我有一个ASP.NET Core WebAPI项目,我正在尝试将配置添加到我通过DI注入的IEmailService
中:
services.AddTransient<IEmailSender, AuthMessageSender>();
AuthMessageSender
的实例如何在配置文件中进行设置?
答案 0 :(得分:25)
您应该使用强类型配置的options模式:
EmailSettings
强类型配置类:public class EmailSettings
{
public string HostName { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
EmailSettings
配置类的配置部分:{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"EmailSettings": {
"HostName": "myhost.com",
"Username": "me",
"Password": "mysupersecretpassword",
}
}
ConfigureServices
类的Startup
调用中,将 appsettings.json 绑定到您的配置类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"
}
}
答案 1 :(得分:1)
推荐的模式是读取您需要的特定配置条目at startup并将它们存储在DI中的选项实例中,并注入特定选项类型into your other components。