1

尽管这个问题在名称上类似于thisthis,但事实并非如此。

我目前正在开发一个库,该库可能需要根据用户的需要进行一些自定义配置。

我创建了一个自定义配置部分,一切正常。

但是,当我调试时,我注意到配置部分构造函数被调用了两次。这不是我的本意。

深入挖掘,我发现它的发生是因为,为了从库中访问配置信息,我使用以下方法:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var section = config.GetSection("myConfigSection");

在此之前,.NET Framework 已经为运行该库的应用程序初始化了配置环境,从而调用了MyConfigSection该类的构造函数。

我的问题是,如何访问已经加载的信息?

为什么类的构造函数被调用两次

因为我不想像上面的代码那样重新加载所有内容。


编辑添加

构造函数被调用两次,即使将上面的代码更改为:

var section = ConfigurationManager.GetSection("myConfigSection");

编辑澄清

这个问题与访问无关MyConfigSection,我可以很好地访问它。

问题是关于为什么类的构造函数被调用两次


再澄清一点

如果类的构造函数被调用两次,则加载过程发生两次。

我根本不希望这种情况发生。这太荒谬了。

是的,Configurationmanager根据我在这个问题中的第一次编辑,我正在调用静态方法。

4

3 回答 3

0

如果父应用程序已经加载了配置,您应该可以直接使用静态GetSection:

ConfigurationManager.GetSection('myConfigSection');

如果那不是您想要的,也许您可​​以更好地解释您的情况。您可能还对 AppSettings 感兴趣 - http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx

于 2010-01-20T04:43:20.950 回答
0

你问了两个问题:为什么 ctor 被调用了两次,以及你如何访问已经加载的配置。

You already pointed out why it's being called twice. The configuration system is parsing the config file when the app is loaded. It makes that config available via ConfigurationManager's static members, including ConfigurationManager.AppSetting and ConfigurationManager.GetSection().

You access the already-loaded config by using these static members.

于 2010-01-20T05:34:50.937 回答
0

After further investigation, the constructor is being called twice because of the following circumstance:

  1. The .NET Framework creates the class when it finds the <section name="..." type="..." /> in the <configSections> element.
  2. If there's a section configured in the app.config or web.config the .NET Framework, creates another instance of the specified class to decode the section and merge with the already created instance.

Although it does work according to the documentation, this behavior might clash with the implementation of a ConfigurationSection if the developer thinks that only one object is created during the lifetime of the application.

So, following this train of thought, if the configuration is specified in, say, the machine.config, app.config and user.config the object will be constructed three times in order to merge everything together.

于 2010-01-20T14:36:22.880 回答