Using values ​​from AppConfig file in C #

selenium = new DefaultSelenium(
    ConfigurationManager.AppSettings["TestMachine"].ToString(),
    4444,       
    ConfigurationManager.AppSettings["Browser"].ToString(),        
    ConfigurationManager.AppSettings["URL"].ToString()
);

Is there an effective way to do this, rather than repeating:

ConfigurationManager.AppSettings[""].ToString()
+5
source share
8 answers

I think it’s best to write a wrapper class with everything related to configuration, especially if you are writing tests. A simple example would be:

public interface IConfigurationService
{
    string GetValue(string key);
}

This approach allows you to mock your configuration when you need it and reduce complexity.

So you can continue:

public void SelTest(IConfigurationService config)
{
    var selenium = new DefaultSelenium(config.GetValue("TestMachine"),
        4444, config.GetValue("Browser"), config.GetValue("URL"));
}

or you can inherit your configuration from the list and reduce text input:

config["Browser"]
+4
source

Yes you can do

ConfigurationManager.AppSettings[""]

Since this is already a string.

ConfigurationManager.AppSettings [ "-" ] , Config, AppSettings .

+1

, :   Properties.Settings.Default.Property

+1

, app/web.config . . - :

public static class MyConfig
{
    /// documentation of config entry
    public static string Browser
    {
      get { return Read("Browser", "some default value"); }
    }

    /// documentation of config entry
    public static int Port
    {
      get { return int.Parse(Read("Browser", "80")); }
    }

    public static string Read(string entry, string defaultValue)
    {
        var entry = ConfigurationManager.AppSettings[entry];
        return string.IsNullOrEmpty(entry) ? defaultValue : entry;
    }
}

:

  • (, /)
  • / (int, bool)
  • .
+1

, ConfigurationSection/ConfigurationElementCollection ConfigurationElement.

ConfigurationElement [ConfigurationProperty("key", IsRequired = true, DefaultValue = "*^%)(@")] , [StringValidator(MinLength = 3)] ..

+1

. , .

0

" " - , , . , , , , .

One template that should be used for simplification is to create the Singleton Application Settings application and load the application load. You essentially create a common hash table (dictionary, etc.) Strings, strings so you can search more easily. But still the overhead of tearing the app settings section.

0
source

You might need to be a little more creative with the class name, but you can do something according to:

class ConfigManager
{
    public static string GetSetting(string name)
    {
        return ConfigurationManager.AppSettings[name].ToString();
    }
}
0
source

All Articles