tags:

views:

284

answers:

2

Hi,

I'm trying to use System.Activator.CreatInstance to Create an object based on the typeName. I'm using the following code:

Object DataInstance = System.Activator.CreateInstance(
                      System.Reflection.Assembly.GetExecutingAssembly().FullName,
                      "CMS.DataAccess.SQLWebSite");
IWebSite NewWebPage = (IWebSite)DataInstance;

SQLWebSite implements IWebSite. But, I get the following error: "Unable to cast object of type 'System.Runtime.Remoting.ObjectHandle' to type 'CMS.DataAccess.IWebSite'." Any ideas where I am going wrong?

+3  A: 

Try unwrap after you call the CreateInstance, i.e.:

Object DataInstance = System.Activator.CreateInstance(System.Reflection.Assembly.GetExecutingAssembly().FullName,
                                    "CMS.DataAccess.SQLWebSite").Unwrap();
            IWebSite NewWebPage = (IWebSite)DataInstance;
Ngu Soon Hui
+2  A: 

If you really want to use the type name and not the strongly typed version of the method then you can do this:


var instance = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("CMS.DataAccess.SQLWebSite");

You could just use :


System.Activator.CreateInstance(typeof(SQLWebSite))

But mabe you are trying not to have to reference the implementation in your code.

Steve Psaltis