Problem with System.Activator.CreateInstance

I am trying to use System.Activator.CreatInstance to create an object based on typeName. I am using the following code:

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

SQLWebSiteimplements IWebSite. But I get the following error: "Unable to overlay an object of type" System.Runtime.Remoting.ObjectHandle "on type" CMS.DataAccess.IWebSite "." Any ideas I'm wrong about?

+3
source share
2 answers

Try unwrapafter the call CreateInstance, i.e.:

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

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


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

You can simply use:


System.Activator.CreateInstance(typeof(SQLWebSite))

mabe .

+3

Source: https://habr.com/ru/post/1727939/


All Articles