如何通过RealProxy透明代理返回一个对象作为返回值?

时间:2010-10-07 22:08:08

标签: vb.net invoke realproxy

我正在开发一个系统,我计划使用RealProxy对象启用对一组对象的拦截方法调用,处理调用,然后返回适当的结果。

这可以找到简单的返回类型,如字符串或整数,但我似乎无法从RealProxy.Invoke方法返回对象。

一切正常。我没有错误,但返回的值总是NOTHING,而不是对象。

我已经编写了尽可能最小的示例代码,并将其包含在下面。

基本上,只需调用RPtest并单步执行即可。 该代码创建一个简单的对象RPTestA,其中包含字符串字段和对象值字段 然后它检索字符串         Dim x = c.Name 哪个工作正常 然后尝试检索对象

Dim r = c.SubObj

总是什么都不返回。

但是,在FieldGetter例程中,此代码为:

'---- the field is an OBJECT type field  
Dim mc = New MethodCallMessageWrapper(Msg)  

'---- create the object  
Dim o = Activator.CreateInstance(t)  
'---- and construct the return message with that object  
Dim r = New ReturnMessage(o, mc.Args, mc.Args.Length, mc.LogicalCallContext, mc)  
Return r  

似乎工作正常,将ReturnMessage的ReturnValue字段设置为上面的Activator.CreateInstance(t)调用创建的对象。

我怀疑它是某种序列化的东西,但我不知所措。

您应该可以立即运行此代码,但只需将其粘贴到新的VB.net项目中即可。

'----------------------------------------------------------------------------
Imports System.Security.Permissions
Imports System.Diagnostics
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Runtime.Serialization
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Activation
Imports System.Runtime.Remoting.Messaging
Imports System.Runtime.Remoting.Proxies


Public Module RPTest
    Public Sub RPTest()
        '---- create a new object that is automatically proxied
        '     See the RPProxyAttribute for details
        Dim c = New RPTestA

        Dim x = c.Name
        'x is returned as a string value just fine
        Dim r = c.SubObj
        '********* PROBLEM IS HERE, r ends up nothing
    End Sub
End Module


'ROOT test object
Public Class RPTestA
    Inherits RPBase

    Public Name As String = "Test Name"
    Public SubObj As RPTestB

End Class


'SUB OBJECT which should be returned as a field value from the root object above
Public Class RPTestB
    Inherits RPBase

    Public SubProperty As String = "SubObj Test Property"
End Class


''' <summary>
''' Base proxyable object class
''' </summary>
''' <remarks></remarks>
<RPProxy()> _
Public MustInherit Class RPBase
    Inherits ContextBoundObject

End Class


<PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
Public Class RPProxy
    Inherits RealProxy

    Private m_target As MarshalByRefObject


    Public Sub New()
        m_target = DirectCast(Activator.CreateInstance(GetType(ConfigRP)), MarshalByRefObject)
        Dim myObjRef = RemotingServices.Marshal(m_target)
    End Sub

    Public Sub New(ByVal classToProxy As Type)
        MyBase.New(classToProxy)
    End Sub


    Public Sub New(ByVal ClassToProxy As Type, ByVal targetObject As MarshalByRefObject)
        m_target = targetObject
        Dim myObjRef = RemotingServices.Marshal(m_target)
    End Sub


    Public Overrides Function Invoke(ByVal msg As IMessage) As IMessage
        Dim returnMsg As IMethodReturnMessage = Nothing

        If TypeOf msg Is IConstructionCallMessage Then
            '---- handle constructor calls
            Dim ConstructionCallMessage = DirectCast(msg, IConstructionCallMessage)
            returnMsg = InitializeServerObject(ConstructionCallMessage)
            Me.m_target = Me.GetUnwrappedServer()
            SetStubData(Me, Me.m_target)
            Return returnMsg

        ElseIf TypeOf msg Is IMethodCallMessage Then
            '---- handle all other method calls
            Dim methodCallMessage = DirectCast(msg, IMethodCallMessage)

            '---- before message processing
            preprocess(methodCallMessage)

            '---- execute the method call
            Dim rawReturnMessage = RemotingServices.ExecuteMessage(Me.m_target, methodCallMessage)

            '---- and postprocess
            returnMsg = postprocess(methodCallMessage, rawReturnMessage)

        Else
            Throw New NotSupportedException()
        End If

        Return returnMsg
    End Function


    'Called BEFORE the actual method is invoked
    Private Sub PreProcess(ByVal msg As IMessage)
        Console.WriteLine("before method call...")
    End Sub


    'Called AFTER the actual method is invoked
    Private Function PostProcess(ByVal Msg As IMethodCallMessage, ByVal msgReturn As ReturnMessage) As ReturnMessage
        Dim r As ReturnMessage
        If Msg.MethodName = "FieldGetter" Then
            r = FieldGetter(Msg, msgReturn)
        ElseIf Msg.MethodName = "FieldSetter" Then
            'na
            r = msgReturn
        ElseIf Msg.MethodName.StartsWith("get_") Then
            'na
            r = msgReturn
        ElseIf Msg.MethodName.StartsWith("set_") Then
            'na
            r = msgReturn
        Else
            r = msgReturn
        End If
        Return r
    End Function


    Private Function FieldGetter(ByVal Msg As IMethodCallMessage, ByVal msgReturn As IMethodReturnMessage) As IMethodReturnMessage
        Dim t = Me.Target.GetType

        '---- This retrieves the type of the field that the getter should retrieve
        t = t.GetField(Msg.InArgs(1), BindingFlags.Instance Or BindingFlags.Public).FieldType

        If t.Name = "String" Then
            '---- just return what the object returned as a result of ExecuteMessage
            Return msgReturn

        ElseIf t.BaseType.Equals(GetType(RPBase)) Then
            '---- the field is an OBJECT type field
            Dim mc = New MethodCallMessageWrapper(Msg)
            '---- create the object
            Dim o = Activator.CreateInstance(t)
            '---- and construct the return message with that object
            Dim r = New ReturnMessage(o, mc.Args, mc.Args.Length, mc.LogicalCallContext, mc)
            Return r

        Else
            Return msgReturn
        End If
    End Function


    Public Property Target() As Object
        Get
            Return Me.m_target
        End Get
        Set(ByVal value As Object)
            Me.m_target = value
        End Set
    End Property
End Class


<AttributeUsage(AttributeTargets.Class)> _
<SecurityPermissionAttribute(SecurityAction.Demand, Flags:=SecurityPermissionFlag.Infrastructure)> _
Public Class RPProxyAttribute
    Inherits ProxyAttribute


    Public Overrides Function CreateInstance(ByVal Type As Type) As MarshalByRefObject
        Dim proxy = New RPProxy(Type)
        Dim transparentProxy = DirectCast(proxy.GetTransparentProxy(), MarshalByRefObject)
        Return transparentProxy
    End Function
End Class

1 个答案:

答案 0 :(得分:3)

嗯,事实证明,这是一个非常简单的解决方案,一旦你工作过了神奇的ReturnMessage构造函数,这是非常误导的!

非常感谢我的一位老同事Rich Quackenbush花了几分钟时间来检查这一点。有时候,你无法看到森林中的树木!

无论如何,在FieldGetter中,我正在做这个

ElseIf t.BaseType.Equals(GetType(RPBase)) Then
        '---- the field is an OBJECT type field
        Dim mc = New MethodCallMessageWrapper(Msg)
        '---- create the object
        Dim o = Activator.CreateInstance(t)
        '---- and construct the return message with that object
        Dim r = New ReturnMessage(o, mc.Args, mc.Args.Length, mc.LogicalCallContext, mc)
        Return r

似乎完全合理,新创建的对象被传递给名为ReturnValue的ReturnMessage构造函数参数。

但不是。实际上你必须创建一个对象数组并将其作为该数组中的3个元素传递,如下所示:

ElseIf t.BaseType.Equals(GetType(RPBase)) Then
        '---- the field is an OBJECT type field
        Dim mc = New MethodCallMessageWrapper(Msg)            '---- create the object
        Dim o = Activator.CreateInstance(t)
        '---- and construct the return message with that object
        Dim r = New ReturnMessage(Nothing, New Object() {Nothing, Nothing, o}, 3, mc.LogicalCallContext, mc)
        Return r

事实证明,这是因为FieldGetter函数被代理“调用”并截获,它的签名是

FieldGetter(StringtypeName,StringfieldName,Object&val)

其中,为了为该调用构造ReturnMessage,意味着它根本没有Returnvalue,而是返回值作为该列表中的第3个参数返回。

因为我实际上并没有调用真正的FieldGetter函数,所以前两个参数(typename和fieldname)是无关紧要的,但是第3个参数是放置返回值的适当位置。

后见之明总是显而易见的!

非常感谢Rich。