将参数传递给Lazy singleton GetInstance

时间:2017-10-01 22:39:24

标签: c# lazy-evaluation

我使用.NET 4's Lazy<T> type方法创建单例实例。但我想将配置文件的三个文件路径传递给返回单例

的属性Instance
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 个答案:

答案 0 :(得分:2)

您能否与我们分享您的课程需要成为单身人士的原因?也许您可以使用IoC容器,在这种情况下,您可以确保在IoC设置中只有一个类实例。

如果你真的想使用单例,可以考虑添加一些init / config方法。在访问实例之前必须初始化你的单例(如果不是则抛出异常),请看下面的内容。我不喜欢这个解决方案,因为Singleton类的用户需要知道init步骤。

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy;

    public static Singleton Instance 
    { 
        get 
        { 
            if (lazy == null)
            {
                throw (...)
            }

            return lazy.Value; 
        } 
    }

    private Singleton(int parameter)
    {
        ...
    }

    public static Init(int parameter)
    {
        if (lazy != null)
        {
            throw (...)
        }

        lazy = new Lazy<Singleton>(() => new Singleton(parameter));
    }
}

答案 1 :(得分:0)

/// <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;
    }
}