跨AppDomain调用在调用者域中执行
我创建一个 AppDomain,在新域中创建一个对象实例,然后调用一个返回包装对象上当前 AppDomain 名称的方法。返回值是主程序域的名称,而不是新创建的程序域的名称。顺便说一句,代码在 VS2010 中作为单元测试执行。
知道测试失败的原因吗?
[Serializable]
public class DomainHelper
{
public string GetDomainName()
{
return AppDomain.CurrentDomain.FriendlyName;
}
}
[TestClass]
public class DomainTests
{
[TestMethod]
public void RemoteCall()
{
var binDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
const string appDomainName = "TEST";
var x = AppDomain.CreateDomain(appDomainName, null, binDir,null, false);
var remoteType = typeof(DomainHelper);
var remote = (DomainHelper) x.CreateInstanceAndUnwrap(remoteType.Assembly.FullName, remoteType.FullName);
Assert.AreEqual(appDomainName, remote.GetDomainName());
}
}
I create an AppDomain, create an instance of an object in the new Domain and call a method that returns the name of the current AppDomain on the wrapped object. the returned value is the name of the main program domain and not the newly created one. By the way the code is being executed as a UnitTest in VS2010.
Any Idea why the test fails?
[Serializable]
public class DomainHelper
{
public string GetDomainName()
{
return AppDomain.CurrentDomain.FriendlyName;
}
}
[TestClass]
public class DomainTests
{
[TestMethod]
public void RemoteCall()
{
var binDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
const string appDomainName = "TEST";
var x = AppDomain.CreateDomain(appDomainName, null, binDir,null, false);
var remoteType = typeof(DomainHelper);
var remote = (DomainHelper) x.CreateInstanceAndUnwrap(remoteType.Assembly.FullName, remoteType.FullName);
Assert.AreEqual(appDomainName, remote.GetDomainName());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为
DomainHelper
是[Serialized]
。这意味着当它跨域时,它会被复制并在调用者的域中重新创建,然后.GetDomainName
在调用者的域中执行。您可以删除[Serialized]
属性并让DomainHelper
从MarshalByRefObject
派生,然后.GetDomainName
将在远程域中执行,或者保留[Serialized]
属性并在构造函数或初始化程序中检索域名,如下所示:初始化程序/构造函数将在远程域中执行,并且相关的当对象跨域时,它设置的字段将被复制。
Because the
DomainHelper
is[Serializable]
. Which means when it crosses domains, it is copied and recreated in the caller's domain, and afterwards.GetDomainName
is executed in the caller's domain. You can either remove the[Serializable]
attribute and have theDomainHelper
derive fromMarshalByRefObject
, then the.GetDomainName
would be executed in the remote domain, or keep the[Serializable]
attribute and retrieve the domain name in a constructor or initializer, like so:The initializer/constructor would then execute in the remote domain, and the relevant fields it sets would be copied when the object crosses domains.