Generic Singleton Pattern in C# with Reflection

Reusable and proven design patterns are crucial to building robust and scalable applications.  I loathe copying and pasting boilerplate code; naturally, I always prefer abstract classes and interfaces when possible.  And frequently, I end up employing a singleton pattern when designing software.  For those who don’t know, a singleton is a class that can only be instantiated once.  This design is especially safe when collaborating with other developers and even on large solo projects, because a class may contain logic or state that should only exist once.  Numerous articles have been written describing a generic implementation in C#, but they almost always fall short in my opinion.  The typical implementation that you can find will appear similar to this (credit to davojc):

*note: do not use this code

public class SingletonProvider<T> where T : new()
{
    SingletonProvider() { }

    public static T Instance
    {
        get { return SingletonCreator.instance; }
    }

    class SingletonCreator
    {
        static SingletonCreator() { }

        internal static readonly T instance = new T();
    }
}

There have been many variations on this implementation, whether striving to more deeply encapsulate the instantiation or to protect the class from threading mishaps.  However, the most glaring problem exists in the fact that the SingletonProvider class applies the new() constraint.   Rather helpfully, this enables the code to instantiate whatever type T is with a blank constructor.

However, this blank constructor must be public to actually work.  This entirely breaks the concept of a singleton pattern because you can then instantiate the class to your heart’s content.  In essence, this implementation not only creates more work for the programmer, but does not provide any of the intended protection!

Fear not, for .NET has reflection!  When there’s no way to do what you want within the bounds of C#, you can always hack it together with reflection.  Thanks to Martin Lapierre for this solution:

*note: you can use any code beyond this point

public static class Singleton<T>
       where T : class
{
  static volatile T _instance;
  static object _lock = new object();

  static Singleton()
  {
  }

  public static T Instance
  {
    get
    {
      if (_instance == null)
        lock (_lock)
        {
          if (_instance == null)
          {
            ConstructorInfo constructor = null;

            try
            {
              // Binding flags exclude public constructors.
              constructor = typeof(T).GetConstructor(BindingFlags.Instance |
                            BindingFlags.NonPublic, null, new Type[0], null);
            }
            catch (Exception exception)
            {
              throw new SingletonException(exception);
            }

            if (constructor == null || constructor.IsAssembly)
            // Also exclude internal constructors.
              throw new SingletonException(string.Format("A private or " +
                    "protected constructor is missing for '{0}'.", typeof(T).Name));

            _instance = (T)constructor.Invoke(null);
          }
        }

      return _instance;
    }
  }
}

Before I explain it, this is how you use it (taken from Martin’s article):

public static SingleInstanceClass Instance
{
  get
  {
    return Singleton<SingleInstanceClass>.Instance;
  }
}

This static property would belong in a SingleInstanceClass class.  Accessing it would make a call to the Instance property of Singleton<T>, which will instantiate (by calling the private constructor using reflection) a class T, store it internally if it has not already done so and of course return the instance. All subsequent calls to Singleton<T>.Instance using this type T will return the original instance. Naturally, the implementation also includes the double-lock check pattern for thread safety. This is preferred over a nested solution to ensure that the constructor may recover in the case that it threw an exception the first time.

The only two caveats I’d like to mention–which are relatively minor–is that this does not ensure that no public constructors exist within the class; and it should be noted that other code that is also using reflection can instantiate this multiple times. However, someone would have to go well out of their way to produce either of these.

This entry was posted in C# and tagged , , , . Bookmark the permalink.
  • Delicious
  • Facebook
  • Reddit
  • StumbleUpon
  • Twitter
  • RSS Feed
  • Google
  • Digg

One Response to Generic Singleton Pattern in C# with Reflection

  1. Pingback: Chenfeisoft | Generic Singleton Pattern in C# with Reflection

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>