在调用者域中执行跨 AppDomain 调用 [英] Cross AppDomain call is executed in caller Domain

查看:34
本文介绍了在调用者域中执行跨 AppDomain 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 AppDomain,在新域中创建了一个对象的实例,并调用了一个方法,该方法返回包装对象上当前 AppDomain 的名称.返回的值是主程序域的名称,而不是新创建的.顺便说一下,代码在 VS2010 中作为 UnitTest 执行.

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());
        }
    }

推荐答案

因为 DomainHelper[Serializable].这意味着当它跨域时,它会在调用者的域中复制和重新创建,然后在调用者的域中执行 .GetDomainName.您可以删除 [Serializable] 属性并让 DomainHelperMarshalByRefObject 派生,然后 .GetDomainName在远程域中执行,或保留 [Serializable] 属性并在构造函数或初始化程序中检索域名,如下所示:

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 the DomainHelper derive from MarshalByRefObject, 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:

[Serializable]
public class DomainHelper
{
    private readonly string _domainIWasConstructedIn = AppDomain.CurrentDomain.FriendlyName;

    public string GetDomainName()
    {
        return _domainIWasConstructedIn;
    }
}

然后初始化器/构造器将在远程域中执行,当对象跨域时,它设置的相关字段将被复制.

The initializer/constructor would then execute in the remote domain, and the relevant fields it sets would be copied when the object crosses domains.

这篇关于在调用者域中执行跨 AppDomain 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆