2010-10-21 119 views
1

我有一个通过MEF使用DLL的可执行文件。我使用使用Configuration Manager.GetSection和Configuration Manager.OpenExe

var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); 
     return appConfig.AppSettings.Settings["Version"].Value; 

现在我想让它这样的DLL可以在DLL的配置文件即席项目成功加载每个DLL的配置文件的AppSettings的钥匙。

因此,我已将此添加到配置文件

<configSections> 
      <section name="AdHocRules" type="BusinessRules.AdHocConfiguration, BusinessRules" /> 
    </configSections> 
       <AdHocRules BaseRuleNumber="ConfigEx1" RuleName="Config Example" EffectiveDate="5/1/2010" Value="Example" IsValid="true"/> 

而且我创建了一个类来读取上面。当我在一个测试控制台应用程序中运行这个不使用DLL时 - 所以一切都编译在一起,一个应用程序配置一切工作正常

但我想使用DLL的配置文件,我不断收到错误

无法转换 类型 'System.Configuration.DefaultSection' 的对象键入 “BusinessRules.AdHocConfiguration

这不是工作; - 它抛出上述

var cm = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); 
AdHocConfiguration adhoc = (AdHocConfiguration)cm.GetSection("AdHocRules"); 

这是代码 - 即席为null,因为它不是从正确的配置文件

AdHocConfiguration adhoc = (AdHocConfiguration)ConfigurationManager.GetSection("AdHocRules"); 


      BusinessRules.Rule r = new BusinessRules.Rule(); 
      r.BaseRuleNumber = adhoc.baserulenumber; 
      r.RuleName = adhoc.rulename; 
      r.EffectiveDate = adhoc.effectivedate; 
      r.Value = adhoc.value; 

任何想法加载?

回答

0

为了使用OpenExeConfiguration方法,其他DLL的配置文件需要和MSDN Reference中提到的可执行文件位于同一个目录中。

您可能需要生成后事件来移动配置文件,但它确实有效。

你也可能需要使用Assembly.GetAssembly(某种类型的通过MEF加载).Location;而不是Assembly.GetExecutingAssembly()。位置,具体取决于您如何使用它。

我有一个示例项目,我使用MEF加载部件,并阅读它们的配置文件。

让我知道你是否仍然有困难