Is it possible to determine if an object works in another AppDomain?

I want to know if I can determine which appdomain created the object. This is for unit test, but also for useful general knowledge. I have the following code snippets (this is sample 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"); } 

Then i call

 Foo myFoo = Create(); 

What I would like to do is figure out which AppDomain method on myFoo will be called to verify that the Create method actually created the new AppDomain. I understand that I can add a method on foo like

 public class Foo { public string appDomainName { get { return AppDomain.CurrentDomain.FriendlyName; } } } 

This will provide me with the application Foo runs on. I do not think this is an elegant solution only for unit test. It would be great if someone could help determine a way like that.

 public string GetAppDomainNameWithDotNetWitchcraft(Foo myFoo) { // Insert voodoo here. } 

EDIT: Thanks for the answers and comments. The question that I asked was answered, and the comments helped me understand where I was wrong. What I really tried to achieve was to verify that the new AppDomain was created.

+7
c # appdomain
source share
1 answer

Well, you can do a little Spelunking through Remoting / Reflection, assuming you are working in full trust. Please note that you need to access private property, and this assumes that the only thing it can find is remote access due to the cross-domain of the application:

  var a = Create(); if (System.Runtime.Remoting.RemotingServices.IsTransparentProxy(a)) { var c = System.Runtime.Remoting.RemotingServices.GetObjRefForProxy(a); var ad = c.ChannelInfo.ChannelData[0]; var propDomainId = ad.GetType().GetProperty("DomainID", BindingFlags.NonPublic | BindingFlags.Instance); var DomainID = propDomainId.GetValue(ad,null); } 

You can then compare this domain identifier yourself to see if it is in your domain. Keep in mind, it is unlikely that you will enter an if statement if it is in your domain (trying to think of circumstances in which you will have a transparent proxy server for an object in your own domain).

+5
source share

All Articles