是否可以判断一个对象是否在不同的 AppDomain 中运行?
我想知道我是否可以知道对象是在哪个应用程序域中创建的。这是用于单元测试的,但也是有用的常识。我有以下代码段(这是用于说明的示例代码)。
public Foo Create()
{
AppDomainSetup appDomainSetup =
new AppDomainSet { ApplicationBase = @"z:\SomePath" }
AppDomain appDomain =
AppDomain.CreateDomain("DomainName", null, appDomainSetup);
return (Foo) appDomain.CreateInstanceAndUnwrap("MyAssembly", "MyClass");
}
然后我调用
Foo myFoo = Create();
我想要做的是找出 myFoo 上的 AppDomain 方法将被调用,以测试 Create 方法是否实际上创建了一个新的 AppDomain。我意识到我可以在 Foo 上添加一个方法,例如
public class Foo
{
public string appDomainName
{
get { return AppDomain.CurrentDomain.FriendlyName; }
}
}
This 将为我提供 Foo 正在运行的应用程序域。我不认为这对于单元测试来说是一个优雅的解决方案。如果有人可以帮助定义这样的方法,那就太好了。
public string GetAppDomainNameWithDotNetWitchcraft(Foo myFoo)
{
// Insert voodoo here.
}
编辑: 感谢您的回复和评论。我提出的问题已经得到解答,评论帮助我意识到我错在哪里。我真正想要实现的是测试是否创建了新的 AppDomain。
I want to know if I can tell what appdomain a object was created in. This is for a unit test but also useful general knowledge. I have the following pieces of code (this is example code for illustration).
public Foo Create()
{
AppDomainSetup appDomainSetup =
new AppDomainSet { ApplicationBase = @"z:\SomePath" }
AppDomain appDomain =
AppDomain.CreateDomain("DomainName", null, appDomainSetup);
return (Foo) appDomain.CreateInstanceAndUnwrap("MyAssembly", "MyClass");
}
I then call
Foo myFoo = Create();
What I would like to be able to do is find out what AppDomain method on myFoo will be called in, to test that the Create method had actually created a new AppDomain. I realise that I can add a method on Foo like
public class Foo
{
public string appDomainName
{
get { return AppDomain.CurrentDomain.FriendlyName; }
}
}
This would provide me the appdomain that Foo is running in. I don't think this is an elegant solution just for a unit test. It would be great if someone could help define a method like.
public string GetAppDomainNameWithDotNetWitchcraft(Foo myFoo)
{
// Insert voodoo here.
}
EDIT:
Thanks for the responses and comments. The question I have asked has been answered and the comments have helped me realised where I was going wrong. What I really was trying to achieve is to test that a new AppDomain is created.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,假设您完全信任您的运行,您可以通过远程处理/反射进行一些探索。请注意,您必须访问私有属性,并且这假设它唯一可以找到的是由于跨应用程序域而进行的远程处理:
然后您可以将该域 ID 与您自己的域 ID 进行比较,以了解它是否在您的域中。请注意,如果 if 语句位于您的域中,您就不太可能输入该语句(尝试考虑一下您对自己域中的对象有透明代理的情况)。
Well, you can do a bit of Spelunking via Remoting/Reflection, assuming your running in full trust. Note that you have to access a private property, and this assumes that the only thing it can find is remoting due to cross app domains:
You can then compare that domain ID to your own to know if it's in your domain. Mind you, it's unlikely you'll enter the if statement if it is in your domain (trying to think of circumstances where you'd have a transparent proxy to an object in your own domain).