Inside Mendz.Library.SingletonBase

In Mendz.Library, one of the classes defined is the SingletonBase. The SingletonBase is an abstract or base class for defining singletons. The singleton instantiation is aimed to be thread-safe. Let's look at how it's done.

Let's jump ahead and look at the full code.

    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 => lazy.Value;
        }
    }

The combinations of static and readonly modifiers do the magic. The static Instance property can be accessed anytime. Lazy makes the instantiation thread-safe. To create a singleton, simply create a class that derives from SingletonBase, give it a private parameterless constructor and you're good to go!

using Mendz.Library;

namespace Test
{
    public class TestSingleton : SingletonBase<TestSingleton>
    {
        private DateTime _created;

        public string Info
        {
            get => Instance.ToString() + " as of " + _created.ToString();
        }

        private TestSingleton() => _created = DateTime.Now;
    }
}

In this sample, TestSingleton can be used as follows.

    Console.WriteLine(TestSingleton.Instance.Info);

In an application domain/runtime, the first call to the Instance property instantiates the singleton. The instantiation of the singleton based on SingletonBase is thread-safe. Having said that, do not confuse it to mean that SingletonBase can make your singleton class thread-safe. Depending on the implementation, your singleton class may not be thread-safe.

Access the latest Mendz.Library codes at GitHub. The latest Mendz.Library binary can be downloaded from NuGet.

Comments