2012-02-28 54 views
3

我有下面的方法在我的DLL類庫是否可以將Appconfig的值作爲Object調用?

private void Download(string filename) 
    { 
    //am calling this value from appconfig 
string ftpserverIp = System.Configuration.ConfigurationManager.AppSettings["ServerAddress"]; 
    // somecode to download the file 
    } 

    Private void Upload(string filename) 
    { 
string ftpserverIp = System.Configuration.ConfigurationManager.AppSettings["ServerAddress"]; 
    // somecode to upload the file 
    } 

就像那個我從AppConfig中爲我所有的方法讓所有的價值,這是任何有效的方法來調用的AppConfig值?

回答

1

它在運行時不會很貴。

但是這將是維護代碼的維護問題。也許一個財產將是有益的。

private string ServerAddress 
{ 
    get { return System.Configuration.ConfigurationManager.AppSettings["ServerAddress"]; } 
} 
private void Download(string filename) 
{ 
// Use ServerAddress 
// somecode to download the file 
} 

Private void Upload(string filename) 
{ 

// somecode to upload the file 
} 

下一個邏輯步驟將是編寫自定義配置部分。

1

如何私人吸氣,以節省打字/ copy'n'pasting:

private string FtpServerIp 
{ 
    get 
    { 
     return ConfigurationManager.AppSettings["ServerAddress"]; 
    } 
} 
+0

哇!真棒所有你的輸入,我會去私人getter。 – Usher 2012-02-28 02:16:58

0

的AppSettings緩存 - 因此它是有效的給他們打電話的方式。

1

這是訪問配置文件的AppSettings部分的首選方式。如果你關心單元測試的目的,你可以將這些值從父容器或類的配置中注入,然後你可以使用值進行測試。或者你可以在你的單元測試項目中有一個單獨的配置。

1

我通常爲我的配置中的appsettings部分中的所有項目創建一個類,例如

public class ConfigSettings 
{ 
    public static string ServerAddress 
    { 
     get 
     { 
      return System.Configuration.ConfigurationManager.AppSettings["ServerAddress"]; 
     } 
    } 

    public static string OtherSetting 
    { 
     get 
     { 
      return System.Configuration.ConfigurationManager.AppSettings["OtherSetting"]; 
     } 
    } 
} 

,然後使用它:

string address = ConfigSettings.ServerAddress; 
相關問題