Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 efficient way to do this, instead of repeating:

ConfigurationManager.AppSettings[""].ToString()
like image 883
Maya Avatar asked Jun 08 '11 14:06

Maya


2 Answers

I think a better idea is to write a wrapper class to everything that deals with configuration, especially if you write tests. A simple example might be:

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

This approach will allow you to mock your configuration when you need it and reduce complexity

So you could proceed with:

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

or you could inherit your configuration from a List and reduce the typing to:

config["Browser"]
like image 107
Stanislav Ageev Avatar answered Nov 02 '22 22:11

Stanislav Ageev


Yes, you can do

ConfigurationManager.AppSettings[""]

As it is already a string.

If you're using ConfigurationManager.AppSettings["Something"] at multiple places, you should create a static Config class, that reads your AppSettings via static properties.

like image 35
mathieu Avatar answered Nov 03 '22 00:11

mathieu