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;
Activator.CreateInstance
, except for one extreme edge-case, always creates a new instance. I suggest that you probably dont want to useActivator
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 ofProxyAttribute
. In the customProxyAttribute
subclass, overrideCreateInstance
to do whatever you want. This is all kinds of evil. But it even works withnew Foo()
.