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

Generic Singleton Design Pattern

By , 31 Aug 2009
 

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)

About the Author

tomer bracksmayer
Program Manager
Israel Israel
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
General[My vote of 1] I dont see the pointmemberCorey Fournier31 Aug '09 - 8:44 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 31 Aug 2009
Article Copyright 2009 by tomer bracksmayer
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid