fizzer
fizzer

Reputation: 2329

problem with System.Activator.CreateInstance

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?

Upvotes: 3

Views: 5930

Answers (2)

Steve Psaltis
Steve Psaltis

Reputation: 665

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.

Upvotes: 3

Graviton
Graviton

Reputation: 83244

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;

Upvotes: 13

Related Questions