2012-03-20 97 views
1

我有一個WinForm項目,其中包含幾個UserControls。此WinForm項目具有對另一個項目(類庫)創建的程序集的引用(稱爲lib.dll),該程序存在於另一個解決方案中。在設計時從類庫中讀取配置文件的替代方法?

現在,UserControls中的幾個調用lib.dll來返回app.config文件中的值。在運行時lib.dll工作正常,並返回必要的數據,但在設計時,我從lib.dll得到一個例外,因爲app.config部分是NULL(例外是由設計)。現在

我可以去通過每個控制和包裝與

if(!DesignMode) { //code } 

調用到lib中的任何代碼,但是這是一個很大的控制去並應用到。有什麼我可以做全球性的,那麼測試DesignMode屬性會更優雅嗎?

編輯

在響應低於離開了兩點意見:所提供的解決方案似乎不工作。導致我遇到問題的程序集與app.config位於同一目錄中。一般的目錄結構看起來像這樣

  • 引用文件夾
  • 配置(文件夾)
  • appsettings.config
  • 的app.config
  • lib.dll

app.config在幾個拉其他配置文件(appsettingscnx字符串等),其中駐留在配置文件離子目錄。在我的例外情況下,我嘗試獲取的值位於app.config引用的其中一個輔助配置文件中。

+1

您是否曾嘗試將app.config文件的副本添加到包含dll的目錄中?只是一種預感。 – Khan 2012-03-20 20:39:02

+0

@Jeff是對的,你可以做兩件事,你可以使app.config成爲另一個項目的鏈接,然後將其設置爲不使用dll(Build Type:None)進行部署。 – 2012-03-20 21:08:43

+0

感謝您的回覆。你的兩個解決方案都不能工作,但我已經更新了我原來的帖子,可能會對這個問題提供更多的信息。 – dparsons 2012-03-21 11:58:10

回答

0

這是一個有趣的問題。一個解決辦法是在這樣一個lib.dll一個靜態類來創建:

public static class Config 
{ 
    private static readonly _param1; 

    static Config() 
    { 
     _param1 = ConfigurationManager.AppSettings["Param1"] ?? "Your default value"; 
    } 

    public static string Param1 
    { 
     get { return _param1; } 
    } 
} 

然後,在你的代碼,寫insted的ConfigurationManager.AppSettings [「參數1」],你將使用Config.Param1。所以你不需要測試屬性DesignMode。

0

有很多方法可以做到這一點,恕我直言。

一想到可以想到的是對於用戶控件使用基於繼承的方法嗎?這樣,在基類中,您可以將該if (DesignMode)檢入,並從那裏進行正確的分支。

// if i were to visualizeyour lib.dll data initializer call like this: 
class BaseUserControl 
{ 
    // i'm guessing that you initialize the data somehow... 
    void InitializeData() 
    { 
     if (!DesignMode) 
     { 
      InitializeDataLocal(); 
     } 
    } 

    protected virtual InitializeDataLocal() 
    { 
     // whatever base behavior you want should go here. 
    } 
} 

// in the derived classes, just put the code you currently have for 
// fetching the data from lib.dll here... 
class UserControl : BaseUserControl 
{ 
    protected override InitializeDataLocal() 
    { 
     // fetch from lib.dll... 

     // optionally invoke some base behavior as well, 
     // if you need to... 
     base.InitializeDataLocal(); 
    } 
}