Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the AppDomain of object

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

like image 401
IS4 Avatar asked May 29 '12 17:05

IS4


People also ask

What is AppDomain in C#?

The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown.

What is AppDomain and CurrentDomain?

The CurrentDomain property is used to obtain an AppDomain object that represents the current application domain. The FriendlyName property provides the name of the current application domain, which is then displayed at the command line.

What is MarshalByRefObject in C#?

MarshalByRefObject is the base class for objects that are marshaled by reference across AppDomain boundaries. If you attempt to transmit an object that derives from this class to another domain (e.g., as a parameter in a method call to a remote machine), an object reference is sent.

What is the difference between AppDomain assembly process and a thread?

A process is an executing application (waaaay oversimplified). A thread is an execution context. The operating system executes code within a thread. The operating system switches between threads, allowing each to execute in turn, thus giving the impression that multiple applications are running at the same time.


2 Answers

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.

like image 140
RobertMS Avatar answered Sep 23 '22 02:09

RobertMS


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.

like image 41
IS4 Avatar answered Sep 21 '22 02:09

IS4