有没有办法基于任意 xml 获取 System.Configuration.Configuration 实例? [英] Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml?
问题描述
我正在尝试对我编写的自定义 ConfigurationSection 进行单元测试,并且我想将一些任意配置 XML 加载到 System.Configuration.Configuration 用于每个测试(而不是将测试配置 xml 放在 Tests.dll.config 文件中.也就是说,我我想做这样的事情:
I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a System.Configuration.Configuration for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this:
Configuration testConfig = new Configuration("<?xml version="1.0"?><configuration>...</configuration>");
MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection");
Assert.That(section != null);
但是,看起来 ConfigurationManager 只会为您提供与 EXE 文件或机器配置相关联的配置实例.有没有办法将任意 XML 加载到 Configuration 实例中?
However, it looks like ConfigurationManager will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?
推荐答案
实际上我发现了一种方法......
There is actually a way I've discovered....
您需要定义一个继承自原始配置部分的新类,如下所示:
You need to define a new class inheriting from your original configuration section as follows:
public class MyXmlCustomConfigSection : MyCustomConfigSection
{
public MyXmlCustomConfigSection (string configXml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(configXml));
DeserializeSection(reader);
}
}
然后,您可以按如下方式实例化 ConfigurationSection 对象:
You can then instantiate your ConfigurationSection object as follows:
string configXml = "<?xml version="1.0"?><configuration>...</configuration>";
MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);
希望对某人有所帮助:-)
Hope it helps someone :-)
这篇关于有没有办法基于任意 xml 获取 System.Configuration.Configuration 实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!