使用预加载的程序集执行CreateInstanceAndUnwrap()

时间:2014-09-16 14:44:53

标签: c#

我已将ServerImporter课定义如下:

public class ServerImporter : MarshalByRefObject
{
    ...
}

我还创建了ServerImporter的实例:

AppDomain _domain = AppDomain.CreateDomain("ServerImporterDomain");
var type = typeof (ServerImporter);
ServerImporter si = _domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName) as ServerImporter;

它运作正常。但我已经加载了我的程序集(有一些预处理),我想用它来创建ServerImporter的实例:

var type = typeof (ServerImporter);
/* My custom Assembly loading (It load an assembly in current domain) */
Assembly assembly = LoadAssemblyFrom(type.Assembly.GetName().Name);
// I want to use this assembly object to do same instance creation

我使用了assembly.CreateInstance()但是当我投了它时,会返回null

1 个答案:

答案 0 :(得分:0)

尝试使用Activator.CreateInstance()

ServerImporter si = (ServerImporter)Activator.CreateInstance(assembly.GetType("ServerImporter"));

另一个AppDomain

ServerImporter si = (ServerImporter)Activator.CreateInstance(domain, type.Assembly.FullName, "ServerImporter");

或者不使用程序集名称,您可以尝试

ServerImporter si = (ServerImporter)Activator.CreateInstance(domain.GetAssemblies().SelectMany(x => x.GetTypes()).Where(x => x.IsEquivalentTo(typeof(ServerImporter)))[0]);