有没有办法让基于XML的任意一个System.Configuration.Configuration实例?没有办法、实例、System、XML

由网友(舔着棉花糖耍着小性格)分享简介:我试图单元测试我写了一个自定义配置节,我想加载一些任意的XML配置成System.Configuration.Configuration 。每个测试(而不是放在Tests.dll.config文件测试配置XML也就是说,我想要做这样的事情:I'm trying to unit test a custom Config...

我试图单元测试我写了一个自定义配置节,我想加载一些任意的XML配置成System.Configuration.Configuration 。每个测试(而不是放在Tests.dll.config文件测试配置XML也就是说,我想要做这样的事情:

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到一个配置实例?

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 :-)

阅读全文

相关推荐

最新文章