CreateInstanceAndUnwrap 和域 [英] CreateInstanceAndUnwrap and Domain
问题描述
我有一个属性,我想将其实例放在其他域中.
I have a property whose instance I want to be in other domain.
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) 中调用.但是当我运行以下代码时,它仍然写入主应用程序域.
This works fine. But I assume all the method calls on _loader instance will invoke in other domain (myDomain). But when I run following code, it still writes main app domain.
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() 吗?我哪里做错了?
Is it because of Unwrap()? Where I am doing wrong?
我知道 AppDomain 创建了单独的内存.我需要的是我的主应用程序运行,它加载不同 AppDomain 中的模块.由于主应用程序还想查看模块的一些活动并与在单独域中运行的对象进行交互,那么实现它的最佳方法是什么.
I understand AppDomain creates seperate memory. What I need is my main application runs, it loads modules in different AppDomain. Since main app also wants to watch some activity of modules and interfare with objects running in seperate domain, what is the best way to achieve it.
推荐答案
如果你想真正运行其他程序集中的代码,你需要让你的 ModuleLoader
类继承自 MarshalByRefObject
.如果您这样做,CreateInstanceAndUnwrap()
实际上将返回一个代理,并且调用将在另一个应用程序域中执行.
If you want to actually run the code in the other assembly, you need to make your ModuleLoader
class inherit from MarshalByRefObject
. If you do that, CreateInstanceAndUnwrap()
will actually return a proxy and the call will be executed in the other appdomain.
如果您不这样做,而是将类标记为 Serializable
(如异常消息所示),CreateInstanceAndUnwrap()
将在另一个appdomain,对其进行序列化,将序列化后的表单传输到原始appdomain,在那里反序列化并调用反序列化实例上的方法.
If you don't do that, and instead mark the class as Serializable
(as an exception message suggests), CreateInstanceAndUnwrap()
will create the object in the other appdomain, serialize it, transfer the serialized form to the original appdomain, deserialize it there and call the method on the deserialized instance.
这篇关于CreateInstanceAndUnwrap 和域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!