【问题标题】:Singleton with Activator.CreateInstance带有 Activator.CreateInstance 的单例
【发布时间】:2013-12-28 09:41:09
【问题描述】:

我有一个实现单例设计模式的类。但是,每当我尝试获取该类的实例时,使用 Activator.CreateInstance(MySingletonType) 只会调用私有构造函数。除了私有构造函数,还有什么方法可以调用其他方法吗?

我的班级定义如下:

public class MySingletonClass{


    private static volatile MySingletonClassinstance;
    private static object syncRoot = new object();
    private MySingletonClass()
            {
                //activator.createInstance() comes here each intantiation.
            }

    public static MySingletonClassInstance
        {
                get
                {
                    if (instance == null)
                    {
                        lock (syncRoot)
                        {
                            if (instance == null)
                                instance = new MySingletonClass();
                        }
                    }
                    return instance;
                }
            }
}

实例化如下:

Type assemblyType = Type.GetType(realType + ", " + assemblyName);
IService service = Activator.CreateInstance(assemblyType, true) as IService;

【问题讨论】:

  • 你为什么要在这里使用激活器?看起来您只是在尝试使用静态属性。
  • 我正在使用独特的服务加载器以动态方式加载一组服务。

标签: c# singleton default-constructor activator


【解决方案1】:

Activator.CreateInstance,除了一个极端的边缘情况,总是创建一个新实例。我建议你可能不想在这里使用Activator

但是,如果你别无选择,hacky hack hack 就是创建一个继承自ContextBoundObject 的类,并用ProxyAttribute 的自定义子类装饰它。在自定义 ProxyAttribute 子类中,覆盖 CreateInstance 以执行您想要的任何操作。这是各种恶行。但它甚至适用于new Foo()

【讨论】:

  • 感谢您的重播。你说的极端情况是什么?
  • @guanabara 那将是第二段,涉及ContextBoundObjectProxyAttribute,完全颠覆了对象创建的方式,可以用来每次返回同一个对象(来自CreateInstance )
【解决方案2】:

嘿,我不知道你为什么要使用反射创建单例类的对象。

单例类的基本目的是它只有一个对象,并且具有全局访问权限。

但是您可以在单例类中访问您的任何方法,例如:

public class MySingletonClass {
    private static volatile MySingletonClass instance;
    private static object syncRoot = new object();
    private  MySingletonClass() { }

    public static MySingletonClass MySingletonClassInstance {
        get {
                if (instance == null) {
                    lock (syncRoot) {
                        if (instance == null)
                            instance = new MySingletonClass();
                    }
                }
            return instance;
        }
    }

    public void CallMySingleTonClassMethod() { }
}

public class program {
    static void Main() {
        //calling a 
        methodMySingletonClass.MySingletonClassInstance
                              .CallMySingleTonClassMethod();      

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    相关资源
    最近更新 更多