如何正确调用单例实现

时间:2015-05-26 10:38:51

标签: c# model-view-controller singleton

我在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();
    }

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

1 个答案:

答案 0 :(得分:1)

通过Controller.Instance进行IMHO访问是针对Controller的客户端,在内部您应该直接使用控制器字段和方法,您不需要知道您的类是用作单例还是不