2010-10-21 52 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加載部件,並閱讀它們的配置文件。

讓我知道你是否仍然有困難