tags:

views:

63

answers:

3

Hi,

I'm still in need of help. I have website settings that I want to load using a singleton pattern. There are so many negatives about using this pattern and every one advices to use Inversion of Control or Dependency Injection. I have not yet worked with IoC or DI.

What is the best way to load website settings once and use it across the whole web application? I thought a singleton pattern would be ideal, but I want to go with best practices. Also, does anyone have any sample code regard using IoC or DI loading website settings? Someone even mentioned that I inject the single's Instance method, but what is the use because it's still a singleton? Also, if anyone has some unit tests regaing this loading of website settings with IoC or DI then it would be appreciated.

I am using C#.

Thanks Brendan

+1  A: 

There are a couple of options, you can use a simple static class :

public class ConfigurationBase
{
    public static string Something
    {
        get { return ConfigurationManager.AppSettings["Something"]; }
    }

    // ....
}

Or try the Castle Dictionary Adapter :

http://codebetter.com/blogs/benhall/archive/2010/07/22/improving-testability-with-the-castle-dictionary-adapter.aspx

Depending on your needs. It's not necessary to over engineer. Keep it simple and readable first.

mathieu
I prefer to load it once to the properties... and return the property...
Garis Suero
Yes, this can be improved, with null checking, etc. I like this approach for very simple projects, as it keeps the magic strings contrained in one place
mathieu
+1  A: 

Singleton is fine in this case if it makes sense to have an instance. Generally it doesn't, and you can just use a static.

Much of the downside of singletons and statics don't exist if they're immutable (those downsides relating to side-effects in global state).

The important thing here is that conceptually, you are looking at the application settings each time you use them. Doing this through a singleton or static just adds a performance boost. If immutability is used to make this impossible to change afterwards, then the only difference between that and looking up the settings each time, is that performance boost.

Conceptually therefore, you aren't introducing global state, you are just improving the performance of global state that already exists. Hence you haven't made things any worse.

Even some who are adamant against global objects (whether singleton or static) make an exception with the flow is one way. Global logging is one-way as the other classes only ever write to it, never read. Global settings are one-way as the other classes only ever read from them, never write.

Jon Hanna