Click here to Skip to main content
15,886,110 members
Articles / Desktop Programming / Win32

Generic Singleton Design Pattern

Rate me:
Please Sign up or sign in to vote.
2.45/5 (6 votes)
31 Aug 2009CPOL1 min read 24.2K   102   20   5
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".

C#
/// <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.
C#
[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.

C#
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)


Written By
Program Manager
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
VMykyt2-Sep-09 23:50
VMykyt2-Sep-09 23:50 
GeneralMy vote of 1 Pin
KiwiPiet1-Sep-09 23:06
KiwiPiet1-Sep-09 23:06 
I agree with Jon Artus
General[My vote of 1] I dont see the point Pin
Corey Fournier31-Aug-09 8:44
Corey Fournier31-Aug-09 8:44 
GeneralMy vote of 1 Pin
Jon Artus31-Aug-09 7:01
Jon Artus31-Aug-09 7:01 
GeneralRe: My vote of 1 Pin
tomer bracksmayer31-Aug-09 9:10
tomer bracksmayer31-Aug-09 9:10 

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

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