是否可以将Appconfig值作为Object调用

  • 本文关键字:Object 调用 Appconfig 是否 c#
  • 更新时间 :
  • 英文 :


我的dll类库中有以下方法

 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值的有效方法吗?

在运行时成本不会很高。

然而,维护代码将是一个维护问题。也许一处房产是有益的。

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
}

下一个合乎逻辑的步骤是编写一个自定义配置部分。

一个私人getter在键入/copy'n'casting:时如何节省

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

我通常会在配置的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;

这是访问配置文件的AppSettings部分的首选方式。如果您关心单元测试的目的,您可以将这些值从配置注入到父容器或类中,然后您可以使用这些值进行测试。或者,您可以在单元测试项目中有一个单独的配置。

AppSettings是缓存的,因此以这种方式调用它们是有效的。