将参数传递给 Lazy singleton GetInstance

问题描述 投票:0回答:2

我正在使用

.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() { } }
    
c# lazy-evaluation
2个回答
5
投票
您能跟我们分享一下您的班级需要单例的原因吗?也许您可以使用 IoC 容器,在这种情况下,您可以确保 IoC 设置中只有您的类的一个实例。

如果你真的想使用单例,也许可以考虑添加一些 init/config 方法。您的单例必须在访问实例之前进行初始化(如果不是,则抛出异常)。我不喜欢这个解决方案,因为 Singleton 类的用户需要以某种方式了解 init 步骤。


-1
投票
/// <summary> /// Singleton class /// </summary> public sealed class Singleton { private static Lazy<Singleton> lazy = null; /// <summary> /// You can use this param to pass to your base class /// </summary> /// <param name="parameter"></param> private Singleton(int parameter) { } /// <summary> /// Creating 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; } }
    
© www.soinside.com 2019 - 2024. All rights reserved.