Properly Implementing the Singleton Pattern

One of the popular coding patterns is called Singleton. I use it currently in my dotNetTips Dev Utility for the configuration object. The pattern is defined:

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

I’ve seen developers implement this pattern in many ways. To make this pattern more consistent, I have added an interface to my dotNetTips.Utility open source project.

public interface ISingleton<T> where T : class
{
    #region Public Properties
    /// <summary>
    /// Returns the instance.
    /// </summary>
    /// <returns>T.</returns>
    T Instance();
    #endregion Public Properties
}

I implement this pattern in another type in this project called Config.

public class Config<T> : ISingleton<T> where T : class
{
    /// <summary>
    /// The instance
    /// </summary>
    private T _instance;
 
    /// <summary>
    /// Returns this instance.
    /// </summary>
    /// <returns>T.</returns>
    public T Instance()
    {
        if (_instance is null)
        {
            this._instance = TypeHelper.Create<T>();
        }
 
        return this._instance;
    }
}

In the code above, the TypeHelper class is also in this project. Use the Singleton pattern to create global object for the project. But use wisely, DO NOT use to store user information etc., especially in a web projects.