My Singleton Base Class

May 28th, 2009 | 0 comments

It seems that for one reason or another I was never able to make a good base class for singletons in C#. They usually wound up with requiring that the derived class call some method to set itself as the static instance. Today, while working on building a fresh new library that I’m going to build a 3D “engine” on top of, I wound up stumbling upon a really nice solution. I realized that I can cast the ‘this’ reference to the type of the singleton. So I wound up with this base class:

public abstract class Singleton<T> where T : class, new()
{
	private static T instance;
	public static T Instance
	{
		get { return instance ?? (instance = new T()); }
	}

	protected Singleton()
	{
		// make sure we only have one instance
		Debug.Assert(
			instance == null,
			string.Format(
				"Singleton of type {0} already instantiated.",
				typeof(T)));

		instance = this as T;

		// validate that the cast worked
		Debug.Assert(
			instance != null,
			string.Format(
				"Singleton of type {0} failed to be instantiated.",
				GetType()));
	}
}

With that laid out my singleton classes don’t have to do anything at all to take advantage of it. The trick is that to make type A a singleton, it simply derives from Singleton<A>. A little confusing initially, but it works quite well in practice. For instance, here’s a simple singleton Log class:

public class Log : Singleton<Log>
{
}

Yep, that’s it. I wanted to illustrate that this base class removes any and all singleton-related code from derived classes. So now to instantiate our single Log we have three options (technically two, but they’re written differently):

var log = new Log(); // manually instantiate

// or use property which instantiates if needed.
// we can use the Log class itself or the base
// Singleton<Log> class to reference it.
var log = Log.Instance;
var log = Singleton<Log>.Instance;

I generally recommend using the Instance properties to make the code more explicit that the object is a singleton, but all three work just fine. If you are manually calling the constructor, the Debug.Assert will fail if you call it multiple times like this:

var a = new Log();
var b = new Log(); // Debug.Assert fails

I’m sure I’m not the first to think up this exact implementation, but since it seems to be a really nice way to stop writing the same singleton boiler plate over and over, I figured I’d share.


Possibly Related Posts

(Automatically Generated)
Catching Exceptions on Xbox 360
Dynamically Refreshed Assets in XNA
Dependency Injection Attributes: On The Class or The Property
A More Robust Exception System
Naming your content

  1. Bjoern
    May 29th, 2009 at 10:10

    A cleaner way would be to use an IoC container instead of a Singleton.

  2. June 2nd, 2009 at 06:48

    Nick,
    Only thing I can think of is that this may not be thread safe. My implementation is a little more involved than yours ( I like the simplicity ) but does provide a threadsafe instatiation.

    http://blog.magenic.com/blogs/michaelc/archive/2006/03/11/Simple-but-it-works.aspx

  3. nstod
    June 4th, 2009 at 12:12

    Nick,

    Got a question for you. Let’s say I wanted a Singleton GameComponent. I obviously can’t inherit from both, and I’m having a hard time thinking up a design without re-creating the Singleton class for each type where I would need to inherit from multiple classes (I have a GameBase class that inherits from Game that I think would be helpful to make a Singleton, as well). Any ideas?

  4. June 4th, 2009 at 12:18

    If you are going to want just one of your components to be a singleton, I’d say just implement the singleton design for that one type. If you have a bunch of components you want to be singletons, I’d make a SingletonGameComponent class which derives from GameComponent and adds in the singleton behavior. You could do the same with DrawableGameComponent to make a SingletonDrawableGameComponent if you wanted.

You must be logged in to post a comment.