I had previously posted a blog on 10/28 about how to get a class library to dynamically find it's own config file...then i realized that i didn't give any instructions on what to do next as far as loading that config file into some sort of object so that your application can use it!
Personally, i would load the configuration file into a singleton object. per msdn documentation, the C# code for this would be:
class Singleton
{
public static Singleton Instance() {
if (_instance == null) {
lock (typeof(Singleton)) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}
protected Singleton() {}
private static volatile Singleton _instance = null;
}i personally find this a bit wordy and complex for what we are really trying to accomplish here. we need one object to share common properties with any subscribing assemblies, for the most part this information isn't going to change, so why waste round trips instantiating a new object each time your assembly needs a property! then i remembered that static types are guaranteed to be type safe, so why go through all that tedious locking code when you can simply do it all in one line, like this:
public sealed class AppConfiguration
{
public static readonly AppConfiguration GetConfig = new AppConfiguration();...
voila! it's as easy as that, you now have a shared instance of your object. bear in mind that all member vars and methods/props will need to be static as well. so now it's time to load our configuration settings. there are numerous ways to parse through an XML document, but again for simplicity (and avoiding looping through the document and storing values in arrays of strings), XPath queries seem to be the easiest way to query for your settings. We go on in our code to creat a *private* constructor (so no one can instantiate your singleton), this will only get called once for the lifetime of the object...
private AppConfiguration()
{
... [code to load the config file into memory, see my previous post on the 28th...
XmlDocument getConfig = new XmlDocument();
try
{
getConfig.Load(_configFileName);
_someMemberVar = getConfig.SelectSingleNode(
"configuration/appSettings/add[@key='ValueYouWantToLoad']/@value").Value;...repeat for all elements
}
now simply expose the member vars as readonly properties, now all calling code can easily read configuration settings.
more to come, it's 6:05PM and i am still at work :-( friggin' long running queries keeping me here late again.
cheerio
j



No comments yet