Skip to main content

The Singleton (Anti)Pattern

There was a time when the Singleton pattern was a trend... until it was officially declared an anti-pattern.

The singleton is defined by Wikipedia as follows:
... a design pattern that restricts the instantiation of a class to one object.
It is also considered an antipattern, a debatable topic, but nonetheless a generally respected notion such that most developers now actively steer away from the singleton as much as possible.

Regardless, I still use it. I even have an abstraction that let me define singletons (cringe).

SingletonBase.cs
using System;

namespace Mendz.Library
{
    public abstract class SingletonBase<T>
        where T : class
    {
        private static readonly Lazy<T> lazy = 
            new Lazy<T>(() => 
                (T)Activator.CreateInstance(typeof(T), true));

        public static T Instance
        {
            get
            {
                return lazy.Value;
            }
        }
    }
}
Which I use to define a singleton class that can store connection string options.

ConnectionStringOptions.cs
using Mendz.Library;
using System.Collections.Generic;

namespace Mendz.Data
{
    public class ConnectionStringOptions : SingletonBase<ConnectionStringOptions>
    {
        private Dictionary<string, string> _connectionStrings;
        public string this[string name]
        {
            get
            {
                return _connectionStrings[name];
            }
            set
            {
                if (_connectionStrings.ContainsKey(name))
                {
                    _connectionStrings[name] = value;
                }
                else
                {
                    _connectionStrings.Add(name, value);
                }
            }
        }

        private ConnectionStringOptions()
        {
            _connectionStrings = new Dictionary();
        }
    }
}
This code defines a singleton ConnectionStringOptions. It contains a dictionary of connection string options which an application can load on startup so that the connection string options can be available anywhere in the active domain. That statement alone opens up a junkful can of worms summarizing exactly why the singleton is an antipattern. Still, I like to keep it handy. I never advertise the SingletonBase to my team. I only have one real use for it in my library and that is for the ConnectionStringOptions.

Comments