如何正确调用单例实现

How to properly call singleton implementation

我在 MVC 项目中得到了这个单例实现:

public sealed class Singleton<T> where T : class {
    private static volatile T _instance;
    private static object _lock = new object();
    static Singleton() {}

    public static T Instance {
        get {
            if (_instance == null)
                lock (_lock) {
                    if (_instance == null) {
                        ConstructorInfo constructor = null;
                        try {
                            // Binding flags exclude public constructors.
                            constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null);
                        }
                        catch (Exception exception) {
                            throw new SingletonException(exception);
                        }
                        if (constructor == null || constructor.IsAssembly) // Also exclude internal constructors.
                            throw new SingletonException(string.Format("A private or protected constructor is missing for '{0}'.", typeof(T).Name));
                        _instance = (T)constructor.Invoke(null);
                    }
                }
            return _instance;
        }
    }
}

然后我有一个控制器和这个实例方法

    public static Controller Instance {
        get { return Singleton<Controller>.Instance; }
    }

在控制器构造函数中我想加载这样的东西

    private Controller() {
       int id = Controller.Instance.SqlManager.GetId();
    }

这当然给了我一个循环,我不知道如何摆脱这个。

恕我直言,通过 Controller.Instance 访问的是 Controller 的客户端,在内部您应该直接使用控制器字段和方法,您不需要知道您的 class 是否是是否作为单例使用。