Question

I have a class which implements the Singleton design pattern. However, whenever i try to get an instance of that class, using Activator.CreateInstance(MySingletonType) only the private constructor is called. Is there any way to invoke other method than the private constructor?

My class is defined as follow:

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

And the instantiation as follow:

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

Solution

Activator.CreateInstance, except for one extreme edge-case, always creates a new instance. I suggest that you probably dont want to use Activator here.

However, if you have no choice, the hacky hack hack hack is to make a class that inherits from ContextBoundObject, and decorate it with a custom subclass of ProxyAttribute. In the custom ProxyAttribute subclass, override CreateInstance to do whatever you want. This is all kinds of evil. But it even works with new Foo().

OTHER TIPS

Hei i do not know why are you creating an object of singleton class using reflection.

the basic purpose of singleton class is that it has only one object and has global access.

however you can access any of your method in singleton class like :

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();      

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top