Get the AppDomain of object
Asked Answered
C

2

10

Is there any way to determine in which AppDomain was an object or ObjectHandle instance created?

Costermonger answered 29/5, 2012 at 17:12 Comment(1)
Good question, but I suspect the answer is no :(Lowpressure
C
4

An object from another app domain is a transparent proxy. It is possible to get the real proxy and access the private field that contains the domain id:

public static int GetObjectAppDomain(object proxy)
{
    RealProxy rp = RemotingServices.GetRealProxy(proxy);
    int id = (int)rp.GetType().GetField("_domainID", BindingFlags.Instance|BindingFlags.NonPublic).GetValue(rp);
    return id;
}

If the list of possible app domains isn't known, here is a way to get the list of all app domains.

Costermonger answered 27/2, 2015 at 21:9 Comment(0)
F
5

If your object "travelled" using (e.g.) serialization from another AppDomain to the current AppDomain then it has essentially been "created" in your current AppDomain. The source AppDomain could be a separate process on the current computer or another process on a remote computer. As far as I am aware, I don't think that the CLR keeps track of that for you, since you are responsible for moving objects between processes. You would probably need to add a field to your class so that you can set and get that information.

Or consider using a LogicalCallContext object that tracks this information for you while travelling with a call accross appdomains. Here is a good blog by Jeffrey Richter about this.

Forgather answered 29/5, 2012 at 17:23 Comment(2)
I don't mean travelling objects. I want to get the AppDomain in which the object is accessible without moving through the barrier. I have an instance of non-serializable class created in some AppDomain. I want to get that domain.Costermonger
@IllidanS4: If you're able to access an instance of a non-serializable class from code you've written, wouldn't that instance be sitting inside AppDomain.CurrentDomain?Travis
C
4

An object from another app domain is a transparent proxy. It is possible to get the real proxy and access the private field that contains the domain id:

public static int GetObjectAppDomain(object proxy)
{
    RealProxy rp = RemotingServices.GetRealProxy(proxy);
    int id = (int)rp.GetType().GetField("_domainID", BindingFlags.Instance|BindingFlags.NonPublic).GetValue(rp);
    return id;
}

If the list of possible app domains isn't known, here is a way to get the list of all app domains.

Costermonger answered 27/2, 2015 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.