我有多个旧版库,这些库通过ConfigurationManager进行自我配置。例如:
var port = ConfigurationManager.AppSettings["service.port"];
新的ASP.Net系统偏向于基于附加的“config.json”文件的强类型模型。示例(摘自Rick Strahl的Web日志):
//from AppSettings.cs
public class AppSettings
{
public string SiteTitle { get; set; }
}
//from config.json
{
"AppSettings": {
"SiteTitle": "WebApplication2",
},
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=blahfoo;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
}
// from Startup.cs
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IHostingEnvironment env)
{
// Setup configuration sources.
var configuration = new Configuration()
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);
configuration.AddEnvironmentVariables();
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// Add Application settings to the services container.
services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
…
}
}
我的问题是:在保持与其他应用程序库的向后兼容性的同时,是否有一种方法可以采用新的ASP.Net 5及其强类型配置方法?或者说,我能否利用我们组合中的常见库而无需重写它们?