[英]C# ASP.Net 5 configuration and backwards compatibility with Class Libraries
我有多個遺留庫,可以通過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和它的強類型配置方法,同時保持與我的其他應用程序庫的向后兼容性?
或者更確切地說,我可以使用我們投資組合中的公共庫而無需重寫它們嗎?
您的問題是您依賴於配置的具體實現,並使用您的類中的ConfigurationManager
的靜態成員,而不是使用適當的依賴注入編寫SOLID實現。
你可以找到一些hacky技巧,你不必更改你的代碼來使用新的配置模型,但我認為你應該幫自己一個忙,並把它作為一個實際重新分解你的代碼和抽象你的機會一個簡單界面背后的當前配置,例如:
public interface IMyAppConfiguration { string Setting1 { get; } string Setting2 { get; } SomeOtherMoreComplexSetting Setting3 { get; } }
然后在需要其中一個設置的每個類中注入此依賴項,並提供一個包裝當前ConfigurationManager類的實現和另一個包裝新配置模型的實現。
這是一個完美的例子,為什么SOLID設計很重要,並且在正確完成時使代碼維護和創新更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.