Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to tell if an object is running in a different AppDomain?

Tags:

c#

.net

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.

like image 750
btlog Avatar asked Mar 09 '10 14:03

btlog


1 Answers

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:

    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 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).

like image 194
Damien_The_Unbeliever Avatar answered Oct 24 '22 02:10

Damien_The_Unbeliever