Click here to Skip to main content
Click here to Skip to main content

Generic Singleton Design Pattern

, 31 Aug 2009
Rate this:
Please Sign up or sign in to vote.
Generic Singleton Design Pattern C#

Introduction

The article describe Generic Singleton Design Pattern, that base on  static constractor behavior.

Background

There are two types of class constructors in C# 'regular constructor' with or without arguments and 'static constructor' without arguments.

Regular Constructor
1. In case the class doesn't write with any constructor, C# provides an implicit default constructor, a constructor with no argument.
2. Constructors can be overloaded
3. Constructors are called in the order of inheritance

Static Constructor
1. A static constructor is thread-safe
2. A static constructor for a class executes at most once in a given application domain
3. An execution of the static field initializers occurs immediately prior to executing that static constructor
4. A static constructors are called in the reverse order of inheritance

Generic Singleton

The Generic Singleton Design Pattern is base principle that "a static constructors are called in the reverse order of inheritance" and "A static constructor for a class executes at most once".

/// <summary>
/// Singleton Template, OOD
/// </summary>
/// <typeparam name="T">class name</typeparam>
/// <example>
/// <code>
/// class MySingleton:Singleton<MySingleton>{}
/// </code>
/// </example>
public class Singleton<T> where T : class
{
         #region Ctor
         protected Singleton(){}
         #endregion
	#region Static Ctor
	static Singleton()
	{
                  Type derivedClassType = typeof(T);
		try
		{ 
                    if (IsConstructorCodeInvalid)
                       throw new SingletonException(string.Format("The Singleton class name:{0} should have only private C'tor.", derivedClassType.Name));

		  ConstructorInfo ctorInfo = typeof(T).GetConstructor(
                                     BindingFlags.Instance | 
                                     BindingFlags.NonPublic |
                                     BindingFlags.DeclaredOnly,
				null, CallingConventions.HasThis,
				Type.EmptyTypes, null);

                    _Instance = (T)ctorInfo.Invoke(null);
		}
                  catch (SingletonException){
                     throw;
                  }
		catch (Exception ex){
                     string err = string.Format(
			"Fail to create : {0} . \n Error Message : {1} \n StackTrace: {2}",
			 typeof(T).Name,
			 ex.InnerException != null ? ex.InnerException.Message : ex.Message,
			 ex.StackTrace);
		  throw new SingletonException(err);
		}
	}
	#endregion

	#region Static public
	static public T Instance { get { return _Instance; } }
	#endregion

         #region Private Static Methods
         static private bool IsConstructorCodeInvalid
         {
            get
            {
                foreach (ConstructorInfo ctorInfo in typeof(T).GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
                {
                    if (!ctorInfo.IsPrivate)
                        return true;
                }
                return false;
            }
         }
         #endregion

	#region Private Members
	static private T _Instance;
	#endregion
}

Error Handling

 In case of error the SingletonException object is throw, there are several cases:

  • There is public, internal or protected c'tor.
  • The private c'tor not exist.
  • Problem while initialize derived  class.
[Serializable]
public class SingletonException : ApplicationException
{
	internal SingletonException(string err)
		: base("Exception while trying to create Singleton.\n " + err) { }
}

 

Using the code

The singleton design pattern is mean single instance of class therefore the c'tor of the derived class, MySingleton, mast be private.

 
public class MySingleton:Singleton<MySingleton>
{
 #region Private Ctor
 private MySingleton(){}
 #endregion

 public string Name {get{return "MySingleton";}}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

tomer bracksmayer
Program Manager
Israel Israel
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 PinmemberVMykyt2-Sep-09 23:50 
GeneralMy vote of 1 Pinmembermwdiablo1-Sep-09 23:06 
General[My vote of 1] I dont see the point PinmemberCorey Fournier31-Aug-09 8:44 
GeneralMy vote of 1 PinmemberJon Artus31-Aug-09 7:01 
GeneralRe: My vote of 1 Pinmembertomer bracksmayer31-Aug-09 9:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 31 Aug 2009
Article Copyright 2009 by tomer bracksmayer
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid