Tag: design pattern

Dependency Injected Singletons… What?

Background

Previously I wrote a bit about singletons. I’m not afraid to say that I think singletons have a time and a place… Okay, I’m afraid to say it, but it’s actually how I feel 🙂 After learning more and more about inversion of control design patterns and programming by interfaces, I started to notice just how inflexible singletons are. When you consider using a singleton, you should be considering both the pros and cons without jumping right into it. Here’s an example of my approach for mixing singletons, programming by interfaces, and a bit of inversion of control.

The Setup

I’m actually surprised you got this far. I’m sure you’re probably just sticking around to see how messed up this could possibly be. I’m actually proud that this little pattern has worked out so well when I’ve used it, so it can’t possibly be that bad.

One major drawback to singletons is that they are often implemented as concrete classes. That is, you ask some class X for it’s instance (via a static property/method) and it provides you it. This doesn’t mix very well with programming by interfaces. So, the first step is to have your singleton return an interface instead of a concrete class. Unfortunately, this on it’s own only provides a few benefits, and it’s really only a minor abstraction layer. You can change your singleton class around all you want, but the only dependencies people are going to see are what’s exposed on the interface. As long as your interface isn’t changing, you’re in a good position. With this change alone, we’ve managed to tackle a bit on programming by interfaces, which makes me just a bit happier.

So, what’s the problem now then? Well, now that I have my singleton returning an interface, the unfortunate truth is it’s always going to be the same class backing that interface. It’s incredibly risky if I start putting some sort of logic in my singleton’s property to get the instance that will return different references that could implement the interface. I mean, once your code is running, you want to make sure you’re always getting the same reference back… or else you’re not using a singleton! The drawback to this is that it completely ruins inversion of control and dependency injection!

 

An Example

Consider that I have a singleton that has information about my application. (If you don’t like my example, then you’ll surely hate using WinForms, because Microsoft does it with their Application class. So, it’s a fair example!) Okay, so if we pretend that we need something just like the Application class in our project, we might create some interface IApplication and create a singleton that returns an instance of an IApplication.

Suppose in one implementation we have, we really want to be using reflection and the assembly information to figure out our application’s information. Our concrete class would implement the IApplication interface but the methods would revolve around using reflection and querying the assembly for what it wants. If we built up a whole framework that used this singleton… We’d be tied to that implementation!

What happens if we go to make another application that wants to use this same framework, but it needs to be able to provide the application information through a configuration file? Well… We’d be pooched! Our singleton that’s used everywhere (and yes, please continue crying about the use of the singleton… Just remember Microsoft’s Application class) and we can’t really do anything about it!

Or can we?

The “Solution”

Okay, so here we are. I’ve demonstrated the problem with a scenario that isn’t too far fetched. How do we fix this crappy situation we’ve got ourselves in by using the dreaded singleton pattern? We use my other best friend: events. Except we use them in a way that makes me cringe. Static events.

Here’s my solution the the above problem:

The Interface:

    public interface IApplication
    {
        string Name { get; }

        string Version { get; }
    }

The Singleton:

    public static class Application
    {
        private static readonly object _instanceLock = new object();
        private static IApplication _instance;

        public static event EventHandler<QueryTypeEventArgs> QueryType;

        public static IApplication Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                        {
                            _instance = CreateInstance();
                        }
                    }
                }

                return _instance;
            }
        }

        private static IApplication CreateInstance()
        {
            var handler = QueryType;
            if (handler == null)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the QueryType event " +
                    "handler was never set.");
            }

            var args = new QueryTypeEventArgs();
            handler.Invoke(null, args);

            if (args.Type == null)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the type has not been " +
                    "provided.");
            }

            // NOTE: here's where things get weird. you need to define your own
            // sort of "contract" for what type of constructor you will allow.
            // you might not even use a constructor here... but you need to
            // define what mechanism the provided type must have to provide
            // you with a singleton instance. i'm a fan of providing a type
            // with a private parameterless constructor, so i'll demonstrate
            // with that. your requirements will change what this section of
            // code looks like.
            if (!typeof(IApplication).IsAssignableFrom(args.Type))
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because the provided type does " +
                    "not implement the IApplication interface.");
            }

            const BindingFlags FLAGS = 
                BindingFlags.CreateInstance | 
                BindingFlags.Instance | 
                BindingFlags.NonPublic;

            var constructors = args.Type.GetConstructors(FLAGS);
            if (constructors.Length != 1)
            {
                throw new InvalidOperationException(
                    "Cannot create an instance because a single private " +
                    "parameterless constructor was expected.");
            }

            return (IApplication)constructors[0].Invoke(null);
        }
    }

The Program (With two types to inject!)

    internal class Program
    {
        private static void Main(string[] args)
        {
            Application.QueryType += (sender, e) =>
            {
                e.Type = typeof(ApplicationB);
            };

            Console.WriteLine(string.Format(
                "Application Name: {0}rnVersion: {1}",
                Application.Instance.Name,
                Application.Instance.Version));

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }
    }

    internal class ApplicationA : IApplication
    {
        private ApplicationA()
        {
        }

        public string Name
        {
            get
            {
                return "Application A (Pretend this was from the assembly info)";
            }
        }

        public string Version
        {
            get { return "1234"; }
        }
    }

    internal class ApplicationB : IApplication
    {
        private ApplicationB()
        {
        }

        public string Name
        {
            get
            {
                return "Application B (Pretend this was from an XML file)";
            }
        }

        public string Version
        {
            get { return "9876"; }
        }
    }

So, if you were to run the program, what outputs would you expect in either case? What happens when you forget to set your event handler? What happens when you set your event handler and don’t provide a type? What if it’s a bad type?

 

Summary


I’m not claiming this is the best approach to solve this problem, and I’m not even encouraging that everyone go ahead and use it. Some of the pros of this are:

  • Advantages of programming by interfaces! You’re only exposing interface definitions to others.
  • Dependency injection capabilities. Inject your “singleton” into other applications.
  • All the goodies related to singletons
  • Easy to use. Just hook up your type to a event handler when your program initializes.

Some of the cons are:

  • All the things people hate about singletons. All of them.
  • Static events are absolutely hideous.
  • You’re giving some other class control of creating your singleton instance.
  • There is no compile time checking or contracts for how your singleton needs to be created.

And now that you know some of the good and some of the bad, can you leverage a design like this? You can check out a working solution I put together for the code and example I described above over at Google Code. Hope you were able to learn something (either good or bad)!


How Do You Structure Your Singletons?

Background

I’ll skip over the discussion about why many people hate singletons (that’s a whole separate can of worms, but worth mentioning) because in the end, it’s not going to get rid of them. A singleton is a design pattern that ensures only one instance of the singleton object can ever be constructed. Often, singletons are made to be “globally accessible” in an application (although, I’m still not confident that this is actually part of the definition of a singleton). There are a handful of different ways to implement singletons… so what are they?

 

The Not-Thread-Safe-Singleton

With singletons, the main goal is to ensure that only one instance can be created. Below is a snippet of singleton code that works, but is not guaranteed in a multi-threaded environment:

    internal class NotThreadSafeSingleton
    {
        private static NotThreadSafeSingleton _instance;

        /// 
        /// Prevents a default instance from being created.
        /// 
        private NotThreadSafeSingleton()
        {
        }

        /// 
        /// Gets the singleton instance (not thread safe).
        /// 
        internal static NotThreadSafeSingleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new NotThreadSafeSingleton();
                }

                return _instance;
            }
        }
    }

The key take away point here is that if this singleton class is accessed across multiple threads, it is possible that two threads perform the null check and begin the constructor at the same time. Because this block of code is not protected with a lock a race condition occurs.

 

The Thread-Safe Singleton

If the key problem with the first example was that it is not safe across threads due to lack of locking… Then it should be pretty obvious that we just need to lock!

    internal class ThreadSafeSingleton
    {
        private static readonly object _instanceLock = new object();
        private static ThreadSafeSingleton _instance;

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private ThreadSafeSingleton()
        {
        }

        /// 
        /// Gets the singleton instance (thread safe).
        /// 
        internal static ThreadSafeSingleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_instanceLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new ThreadSafeSingleton();
                        }
                    }
                }

                return _instance;
            }
        }
    }

That looks sort of weird though, doesn’t it? The double-check serves two purposes: a required check for thread safety and a performance optimization! The check inside of the lock actually guarantees that a single instance is created across threads. However, the check outside is an optimization because after the first instance is created, there’s overhead to acquiring the lock just to check if the instance exists.

For what it’s worth, this is actually my preferred method of coding singletons. I’ve been coding them like this for a while in C#, and I find they work nicely. However, I stumbled upon a posting by John Skeet (essentially, a programming god) who’s done a much better job at documenting singleton patterns than I have. In his analysis, he actually notes some drawbacks to this pattern. Firstly, he mentions it doesn’t work in Java, which is a great point. I primarily code in C#, but this is still important to acknowledge. Secondly, he calls upon ECMA CLI memory specifications that state it’s not guaranteed to actually be thread safe without memory barriers. This was slightly out of my comfort zone, so I admit I still have yet to look into this. Finally, I do agree that the pattern is easy to get wrong for more junior developers and as for performance, I’ve never considered it an issue at all. (Hopefully by now you’ve come back from his write-up to finish mine!)

 

Generic Singleton: A Quick Hand At It…

One of the big drawbacks I saw with the thread safe singleton implementation that I favour is the amount of boilerplate code. Every time I want a new singleton class, I have to code basically everything you see in the previous section. It’s redundant and I don’t want to do it. I can hear the singleton-haters saying “so STOP making them!” but as I said, that’s a discussion for a later post.

I decided I’d have a quick attempt at making a generic singleton! Check out my implementation below (and be warned that I flipped some condition checks in order to try and reduce the width of the text to fit nicely here…):

    internal class Singleton<T> where T : class
    {
        private static readonly object _instanceLock = new object();
        private static T _instance;

        /// 
        /// Prevents a default instance of the class from being created.
        /// 
        private Singleton()
        {
        }

        /// 
        /// Gets the singleton instance (thread safe).
        /// 
        internal static T Instance
        {
            get
            {
                if (_instance != null)
                {
                    return _instance;
                }

                lock (_instanceLock)
                {
                    if (_instance != null)
                    {
                        return _instance;
                    }

                    const string SINGLETON_EXCEPTION_MSG =
                            "A single private parameterless constructor is required.";

                    var constructors = typeof(T).GetConstructors(
                        BindingFlags.Public |
                        BindingFlags.CreateInstance |
                        BindingFlags.Instance);

                    if (constructors.Length > 0)
                    {
                        throw new Exception(SINGLETON_EXCEPTION_MSG);
                    }

                    constructors = typeof(T).GetConstructors(
                        BindingFlags.NonPublic |
                        BindingFlags.CreateInstance |
                        BindingFlags.Instance);

                    if (constructors.Length != 1 ||
                        constructors[0].GetParameters().Length > 0 ||
                        !constructors[0].IsPrivate)
                    {
                        throw new Exception(SINGLETON_EXCEPTION_MSG);
                    }

                    _instance = (T)constructors[0].Invoke(null);
                    return _instance;
                }
            }
        }
    }

Doesn’t look to shabby, right? You simply need to create a class with *only* a private constructor and everywhere you want access to the singleton, you say Singleton.Instance. It’s that easy.

Unfortunately, this isn’t as good as I initially hoped. Can you think of an example where this approach breaks down? My hint to you is everything you need to break it is posted right here. Unfortunate really because I thought I was onto something good there! 🙂 In reality, it may not be a bad foundation for your singleton implementations if you don’t like the boiler plate code I listed above.

 

Summary

There are many ways to write singletons, and some are clearly more robust than others. I’ve only shown you a couple here, but John Skeet’s post has a handful more which he prefers. It’s hard to argue with what he’s written (although, I’m not actually fond of his fourth implementation which he likes) because he’s done a great analysis on them. In the end, it’s important to know what a singleton actually is, when you might want to use it, and what the differences actually mean in various implementations.


  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress