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

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

问题描述

我尝试单元测试我编写的自定义ConfigurationSection,我想将一些任意配置XML加载到 System.Configuration.Configuration 每个测试(而不是把测试配置xml放在Tests.dll.config文件中,也就是说,I 'd喜欢这样做:

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?

推荐答案

您需要定义一个继承自原始配置部分的新类,如下所示:

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

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

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