我正在尝试学习ASP.NET 5.我在Mac OS X上使用它。此时,我有一个如下所示的config.json文件:
config.json
{
"AppSettings": {
"Environment":"dev"
},
"DbSettings": {
"AppConnectionString": "..."
},
"EmailSettings": {
"EmailApiKey": "..."
},
}
我试图弄清楚如何将这些设置加载到Startup.cs中的配置文件中。目前,我有一个看起来像这样的文件:
Configuration.cs
public class AppConfiguration
{
public AppSettings AppSettings { get; set; }
public DbSettings DbSettings { get; set; }
public EmailSettings EmailSettings { get; set; }
}
public class AppSettings
{
public string Environment { get; set; }
}
public class DbSettings
{
public string AppConnectionString { get; set; }
}
public class EmailSettings
{
public string MandrillApiKey { get; set; }
}
然后,在Startup.cs中,我有以下内容:
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment environment)
{
var configuration = new Configuration().AddJsonFile("config.json");
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppConfiguration>(Configuration);
}
但是,这种方法不起作用。基本上,它就像它不知道如何在.json和Config类之间映射。我该怎么做?
我真的很想继续使用DI方法,这样我就可以更有效地测试我的应用程序。
谢谢
答案 0 :(得分:4)
在Startup
课程中,首先指定配置来源:
private readonly IConfiguration configuration;
public Startup(IHostingEnvironment env)
{
configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
}
env.EnvironmentName
类似"development"
或"production"
。假设它是"development"
。该框架将首先尝试从config.development.json
提取配置值。如果请求的值不存在,或者config.development.json
文件不存在,那么框架将尝试从config.json
中提取值。
将您的config.json
部分配置为以下服务:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(configuration.GetSubKey("AppSettings"));
services.Configure<DbSettings>(configuration.GetSubKey("DbSettings"));
services.Configure<EmailSettings>(configuration.GetSubKey("EmailSettings"));
}
在Configure<T>(IConfiguration)
上调用IServiceCollection
会在依赖项注入容器中注册类型IOptions<T>
。请注意,您不需要AppConfiguration
课程。
然后指定要像这样注入的依赖项:
public class EmailController : Controller
{
private readonly IOptions<EmailSettings> emailSettings;
public EmailController (IOptions<EmailSettings> emailSettings)
{
this.emailSettings = emailSettings;
}
public IActionResult Index()
{
string apiKey = emailSettings.Options.EmailApiKey;
...
}
}
答案 1 :(得分:1)
您可以在应用程序的任何位置使用Environment
类来简单地访问config属性Configuration
的值。
var environment = Configuration["AppSettings:Environment"];
但是如果你想通过类的属性访问它,你可以这样做
public class AppSettings
{
public string Environment
{
get
{
return new Configuration().Get("AppSettings:Environment").ToString();
}
set;
}
}
注意我没有在setter中设置Environment
的值,因为此值将在config.json
中,因此无需在setter中设置此值
有关详细信息,请查看此article。
答案 2 :(得分:0)
尝试使用OptionsModel
。它允许强类型模型绑定到配置。
class AppSettings
{
public string SomeSetting {get;set;}
}
var configuration = new Configuration().AddJsonFile("config.json");
var opt = ConfigurationBinder.Bind<AppSettings>(configuration);
opt.SomeSetting