C# CreateInstanceAndUnwrap和域
我有一个属性,我希望它的实例位于其他域中C# CreateInstanceAndUnwrap和域,c#,plugins,appdomain,C#,Plugins,Appdomain,我有一个属性,我希望它的实例位于其他域中 public ModuleLoader Loader { get { if(_loader == null) _loader = (ModuleLoader)myDomain.CreateInstanceAndUnwrap( this.GetType().As
public ModuleLoader Loader
{
get
{
if(_loader == null)
_loader = (ModuleLoader)myDomain.CreateInstanceAndUnwrap(
this.GetType().Assembly.FullName,
"ModuleLoader",
false,
System.Reflection.BindingFlags.CreateInstance,
null,
null,
null,
null);
System.Diagnostics.Debug.WriteLine("Is proxy={0}",
RemotingServices.IsTransparentProxy(_loader));
//writes false
_loader.Session = this;
return _loader;
}
}
这个很好用。但我假设_loader实例上的所有方法调用都将在其他域(myDomain)中调用。但当我运行以下代码时,它仍然会写入主应用程序域
public void LoadModule(string moduleAssembly)
{
System.Diagnostics.Debug.WriteLine("Is proxy={0}",
RemotingServices.IsTransparentProxy(this));
System.Diagnostics.Debug.WriteLine(
AppDomain.CurrentDomain.FriendlyName);
System.Diagnostics.Debug.WriteLine("-----------");
}
是因为Unwrap()吗?我哪里做错了
我知道AppDomain会创建单独的内存。我需要的是我的主应用程序运行,它加载不同AppDomain中的模块。由于主应用程序还希望观察模块的某些活动,并与在不同域中运行的对象进行交互,因此最好的实现方法是什么。如果您希望在其他程序集中实际运行代码,则需要使您的
ModuleLoader
类继承自。如果这样做,CreateInstanceAndUnwrap()
将实际返回一个代理,调用将在另一个appdomain中执行
如果您不这样做,而是将类标记为可序列化的(如异常消息所示),CreateInstanceAndUnwrap()
将在另一个appdomain中创建对象,序列化它,将序列化的表单传输到原始appdomain,在那里反序列化它,并在反序列化的实例上调用该方法