这是我为解决此问题而提出的解决方案:
我创建了一个从 IConfigurationSource 派生的新类 XmlConfigurationSource:
public class XmlConfigurationSource : IConfigurationSource
{
private string _xml;
public XmlConfigurationSource(string xml)
{
_xml = xml;
}
//Other IconfigurationSource members omitted for clarity.
//Also, I'm not using them so I didn't implement them
public ConfigurationSection GetSection(string sectionName)
{
//Since my solution is specific to validation, I'm filtering for that here.
//This could easily be refactored for other EntLib blocks
//SerializableConfigurationSection object instead of XmlValidatorSettings
if (sectionName != "validation")
return null;
XmlValidatorSettings x = new XmlValidatorSettings(_xml.ToString());
return x;
}
}
XmlValidatorSettings 类是让它工作的关键。这是一个从 ValidationSettings 派生的非常简单的类:
public class XmlValidatorSettings : ValidationSettings
{
public XmlValidatorSettings(string configXml)
{
XDocument doc = XDocument.Parse(configXml);
DeserializeSection(doc.CreateReader());
}
}
要使用此代码,您需要参考 EntLib 通用和验证 DLL。希望其他人从中受益!