Is it possible to pass a App setting "string" in the web.config to a Common C# class?
views:
610answers:
4In any class you can use ConfigurationManager.AppSettings["KeyToSetting"]
to access any value in the element of web.config (or app.config)
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.
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;
}
}
}
It's possible to pass something from the web.config in the asp code as well, via something like this (using a SqlDataSource
as an example):
<asp:SqlDataSource ConnectionString="<%$ ConnectionStrings:NameOfConnectionString %>" />
See here for more detail: http://weblogs.asp.net/owscott/archive/2005/08/26/using-connection-strings-from-web.config-in-asp.net-v2.0.aspx
I'm all about code-behind, so I wouldn't do it this way, but it's good to know about anyway.