【问题标题】:howto add a transparent client side proxy to a remote object如何将透明客户端代理添加到远程对象
【发布时间】:2008-10-20 18:18:20
【问题描述】:

我遇到了一个小问题,我想不通。我有一个服务器端 MarshalByRefObject,我试图在客户端包装一个透明代理。这是设置:

public class ClientProgram {
    public static void Main( string[] args ) {
        ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
        test = (ITest)new MyProxy( test ).GetTransparentProxy();
        test.Foo();
    }
}

public class MyProxy : RealProxy {

    private MarshalByRefObject _object;

    public MyProxy( ITest pInstance )
        : base( pInstance.GetType() ) {
        _object = (MarshalByRefObject)pInstance;
    }

    public override IMessage Invoke( IMessage msg ) {
        return RemotingServices.ExecuteMessage( _object, (IMethodCallMessage)msg );
    }
}

问题是调用 RemotingServices.ExecuteMethod 时,抛出异常并显示消息“ExecuteMessage 只能从对象的本机上下文中调用。”。谁能指出如何让它正常工作?我需要在远程对象的方法调用之前和之后注入一些代码。干杯!

【问题讨论】:

    标签: c# proxy remoting


    【解决方案1】:

    知道了。你的评论让我走上了正轨。关键是解开代理并在其上调用调用。谢谢!!!!!!

    public class ClientProgram {
            public static void Main( string[] args ) {
                ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
                ITest test2 = (ITest)new MyProxy( test ).GetTransparentProxy();
                test2.Foo();
            }
        }
    
    public class MyProxy : RealProxy {
    
        private object _obj;
    
        public MyProxy( object pObj )
            : base( typeof( ITest ) ) {
            _obj = pObj;
        }
    
        public override IMessage Invoke( IMessage msg ) {
            RealProxy rp = RemotingServices.GetRealProxy( _obj );
            return rp.Invoke( msg );
        }
    }
    

    【讨论】:

      【解决方案2】:

      我不久前做过,忘记了确切的过程,但尝试使用 RemotingServices.GetRealProxy 从 test 对象获取代理并将其传递到您的 MyProxy 并调用它。

      类似这样的:

      ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" );
      RealProxy p2 = RemotingServices.GetRealProxy(test)
      test = (ITest)new MyProxy( p2 ).GetTransparentProxy();
      test.Foo();
      

      您必须更新 MyProxy 类才能与直接类的 RealProxy 一起使用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-04
        • 2020-02-03
        • 2023-03-17
        • 2012-05-06
        相关资源
        最近更新 更多