ASP.NET 3.5
我们的解决方案中的类引用了ConfigurationManater.AppSettings [“”]以获取appSettings(来自web.config)。
我们决定对此并不满意。 人们在代码中错误地键入appSetting键名(编译得很好),跟踪用法很麻烦。 然后在整个代码库中存在重复的字符串,因为您在整个地方引用了相同的appSettings。
因此,我们决定只允许一个类引用ConfigurationManager,并且当需要某个appSetting的值时,其余的解决方案将引用该类。 ConfigurationManater.AppSettings [“”]是静态的,因此我们从单个Settings类中暴露了一堆静态只读属性。
public class Settings {
public static string Foo {
get {
return ConfigurationManager.AppSettings["Foo"];
}
}
}
这非常有效,直到我们需要在测试中模拟设置。 我们创建了一个界面来启用我们的模拟(这是一个错误吗?)。
public interface ISettings {
string Foo {
get;
set;
}
}
public class Settings : ISettings {
public string Foo {
get {
return ConfigurationManager.AppSettings["Foo"];
}
}
}
现在我们将ISettings实例注入为使用设置值的对象的依赖项(类/接口在每个人都可以引用而没有问题的项目中)。
在我们无法注入现有实例的地方(例如Global.asax),我们在静态字段中构造一个新实例。
鉴于所有这些,你会建议我们改变什么,为什么?
ASP.NET 3.5
Classes throughout our solution referenced ConfigurationManater.AppSettings[""] to get appSettings (from web.config).
We decided we weren't happy with that. Folks were mistyping appSetting key names in code (which compiled fine), and it was cumbersome to track usages. And then there's the duplicated strings throughout the codebase as you reference the same appSettings all over the place.
So, we decided that only one class would be allowed to reference the ConfigurationManager, and the rest of the solution would reference that class when it needed the value of a certain appSetting. ConfigurationManater.AppSettings[""] was static, so we exposed a bunch of static read-only properties off of our single Settings class.
public class Settings {
public static string Foo {
get {
return ConfigurationManager.AppSettings["Foo"];
}
}
}
That worked pretty well, until we needed to mock the settings in our tests. We created an interface to enable our mocking (was this a mistake of any kind?).
public interface ISettings {
string Foo {
get;
set;
}
}
public class Settings : ISettings {
public string Foo {
get {
return ConfigurationManager.AppSettings["Foo"];
}
}
}
And now we're injecting the ISettings instance as a dependency of the objects which use settings values (the class/interface are in a project that everyone can reference without problems).
In places where we can't inject an existing instance (e.g. Global.asax), we construct a new instance into a static field.
Given all of that, what would you recommend we change, and why?
请发表评论