Passing parameters to Lazy singleton GetInstance

Viewed 5834

I am using the .NET 4's Lazy<T> type method to create a singleton instance. But I want to pass three file paths of configuration files to the property Instance that returns the singleton

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}
2 Answers

Can you share with us the reason why your class needs to be a singleton? Perhaps you can use an IoC container, in such case you can ensure that there's just one instance of your class in IoC set-up.

If you really want to use a singleton, maybe think about adding some init/config method. Your singleton would have to be initialized before accessing the instance (throw an exception if it isn't). I don't like this solution, as users of the Singleton class need to know somehow about the init step.

/// <summary>
/// Single ton class
/// </summary>
public sealed class Singleton
{
    private static Lazy<Singleton> lazy = null;
    /// <summary>
    /// You can use this param even  you can pass to your base class
    /// </summary>
    /// <param name="parameter"></param>
    private Singleton(int parameter)
    {

    }
    /// <summary>
    /// Creaeting single object
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public static Singleton CreateSingletonObj(int parameter)
    {
        if (lazy == null)
        {
            lazy = new Lazy<Singleton>(() => new Singleton(parameter));
        }
        return lazy.Value;
    }
}
Related