c# – MarshalByRefObject is passed by reference or makes a copy?


There are 2 AppDomain with LoaderOptimization = LoaderOptimization.MultiDomainHost .
There is a common assembly, say Common.dll , that is loaded in AppDomain1 and AppDomain2.
There is a class in the Common.dll assembly:

class MethodArgs:MarshalByRefObject  
    public string MethodName { get; private set; }

When transferring an instance of this class from AppDomain1 to AppDomain2, is the transfer by reference or is it copied and then a link is made?


Despite the class name MarshalByRefObject , passing is not entirely by reference. A simplified diagram looks something like this:

  1. On the caller, two proxies are created – System.Runtime.Remoting.Proxies.__TransparentProxy , which by all MethodArgs is an object of the original type – MethodArgs , and RealProxy , which can transfer the call to another domain.
  2. Runtime intercepts all calls to proxy methods and properties, and checks if their real object for this __TransparentProxy in a different domain. If the object is in the same domain, then a simple method call occurs.
  3. Otherwise, the runtime collects all the parameters, wraps them in an IMessage, and sends it to the RealProxy.Invoke(...) method.
  4. RealProxy (more precisely, its implementation for cross-domain calls) transfers the call to another domain, deserializes the parameters and calls the method on the real object.

__TransparentProxy is a system class and its behavior cannot be changed.

The RealProxy behavior, on the other hand, can be completely customized, which allows it to be used, for example, tracing / substituting the results of calls – creating mocks. Or for load balancing, redirecting calls from one __TransparentProxy to multiple real objects.

The LoaderOptimization.MultiDomainHost has no effect on the behavior of MarshalByRefObject .

More details about the proxy mechanism in remouting:

Scroll to Top