Singleton<T>

Advanced implementation of the generic Singleton implementation (see also SharedInstance). Uses reflection, custom attributes and “lazy initialization” to provide a powerful way to create and initialize your singletons.

E.g:

public class UserPreferences : IXmlSerializable, ISupportLazyInitialization
{
    ..
 
    public virtual void Initialize()
    {
        try
        {
            string location=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) 
                            + "\\Codoxide\\preference.xml";
 
            if (File.Exists(location))
                using (XmlReader reader = XmlReader.Create(location))
                {
                    reader.ReadToFollowing("Preferences");
                    this.ReadXml(reader);
                    reader.ReadEndElement();
                }
        }
        catch (Exception ex)
        {
            throw new InvalidConfigurationException(
                        "Exception occurred while loading the preferences from disk", ex);
        }
    }
    ..
 
    private UserPreferences() {}
}
 
...
 
Console.WriteLine(Singleton<UserPreferences>.Instance.BackgroundColor);
Back to top
singleton.txt · Last modified: 2008/12/12 16:10 by sameeraperera