-->

Transparent proxy to original type

2019-05-10 18:39发布

问题:

I have an run time object of type {System.Runtime.Remoting.Proxies.__TransparentProxy} which is created from an instance of class which is inherited from ContextBoundObject. This class raise an event to some other object, I need to convert this proxy object to original object. All objects are in default AppDomain on single system.

public abstract class ObjectBase : ContextBoundObject, IObjectBase
{
}

public IMessageSink GetObjectSink(MarshalByRefObject o, IMessageSink next)
        {
            _context = (ObjectBase)o;// as ObjectBase; does not give any error but type remains 
/// transparent proxy in VS watch window.
// no property to get the  underlying type of the proxy
             return _aspect;
        }

How to convert them into original object? Why proxy is cretaed if running on same memory

回答1:

You can get the RealProxy instance for the transarent proxy by calling MarshalServices.GetRealProxy(), but getting the server object reference is then harder because the default RealProxy only has non-public members exposing this reference (a protected method GetUnwrappedServer() and an internal property UnwrappedServerObject). You can either get to those if the RealProxy is implemented by yourself or via reflection (if you have enough trust to perform this).



回答2:

You shouldn't get the actual reference to an Context bound object. Evan you get the reference using reflection/internal API you will get unexpected behavior (cause you break the rules). You can get more insides about context object using google.

I think you have an issue in your actual architecture/design. You can not have an object to be "agile" and "context bound" at the same time. A solution is to split your big object in 2 (one context bound and another agile, and hold a reference(s) between them).

So when you get the reference of the "agile" one (which inherits from MArshallByRefObject) into the creation AppDomain you get the real object reference, not a proxy. (this is the MarshallByRefObject definition)