有没有办法让基于XML的任意一个System.Configuration.Configuration实例? [英] Is there a way to get a System.Configuration.Configuration instance based on arbitrary xml?

查看:138
本文介绍了有没有办法让基于XML的任意一个System.Configuration.Configuration实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图单元测试我写了一个自定义配置节,我想加载一些任意的XML配置成<一个href="http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx">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);

不过,它看起来像<一个href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx">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 :-)

这篇关于有没有办法让基于XML的任意一个System.Configuration.Configuration实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆