Question

Is it possible to pass a App setting "string" in the web.config to a Common C# class?

Was it helpful?

Solution

Of course it's possible - but the thing to keep in mind is that a properly designed class (unless it's explicitly designed for ASP.NET) shouldn't know or care where the information comes from. There should be a property (or method, but properties are the more '.NET way' of doing things) that you set with the string value from the application itself, rather than having the class directly grab information from web.config.

OTHER TIPS

In any class you can use ConfigurationManager.AppSettings["KeyToSetting"] to access any value in the element of web.config (or app.config)

If you have configuration values that are used in many places consider developing a Configuration class that abstracts the actual loading of the configuration items and provides strongly typed values and conversions, and potentially default values.

This technique localizes access to the configuration file making it easy to switch implementations later (say store in registry instead) and makes it so the values only have to be read from the file once -- although, I would hope that the configuration manager would be implemented this way as well and read all values the first time it is used and provide them from an internal store on subsequent accesses. The real benefit is strong typing and one-time-only conversions, I think.

public static class ApplicationConfiguration
{
    private static DateTime myEpoch;
    public static DateTime Epoch
    {
       get
       {
          if (myEpoch == null)
          {
              string startEpoch = ConfigurationManager.AppSettings["Epoch"];
              if (string.IsNullOrEmpty(startEpoch))
              {
                 myEpoch = new DateTime(1970,1,1);
              }
              else
              {
                 myEpoch = DateTime.Parse(startEpoch);
              }
          }
          return myEpoch;   
       }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top