我正在尝试注入一个定义为
的配置阅读器的模拟器public interface IConfigurationReader
{
string GetConfigSetting(string settingName);
}
并且在实现中看起来像:
private class MyConfig : cherry.Framework.IConfigurationReader
{
public string GetConfigSetting(string settingName)
{
return ConfigurationManager.AppSettings[settingName];
}
}
问题当然是这需要我在这个项目中有一个app.config文件。理想情况下,我想做一些事情:
return Foo("c:\temp\someconfig.config\",settingName);
是否有内置方法将采用文件名并返回所需的设置?
答案 0 :(得分:0)
XML to linq是我的朋友:
private class MyConfig : cherry.Framework.IConfigurationReader
{
private String ConfigFile { get; set; }
public MyConfig(String configFile)
{
ConfigFile = configFile;
}
public string GetConfigSetting(string settingName)
{
var setting = XDocument.Load(ConfigFile).Descendants("add").Select(s => new
{
AppKey = s.Attribute("key"),
AppValue = s.Attribute("value")
}).FirstOrDefault(x => x.AppKey.Value == settingName);
if (setting == null)
{
throw new Exception("key not found!");
}
else
return setting.AppValue.Value;
}
}