Reputation: 21
I'm trying to create a proxy using a RealProxy extension. I had no problem in forwarding calls and intercepting them. However, I also wanted to intercept the instantiation of the class being proxied, so I tried to override the instance creation in a ProxyAttribute derived class.
Here is the code:
namespace T1
{
[ProxiableProxy]
class Proxiable : ContextBoundObject
{
public void DoStuff(string test)
{
return;
}
}
class ProxiableProxyAttribute : ProxyAttribute
{
public override MarshalByRefObject CreateInstance(Type serverType)
{
return (Proxiable)new MyProxy(serverType).GetTransparentProxy();
}
public override RealProxy CreateProxy(ObjRef objRef, Type serverType, object serverObject, System.Runtime.Remoting.Contexts.Context serverContext)
{
return new MyProxy(serverType);
}
}
class MyProxy : RealProxy
{
public MyProxy(Type myType) : base(myType)
{
}
public override System.Runtime.Remoting.Messaging.IMessage Invoke(IMessage myIMessage)
{
Console.WriteLine("MyProxy.Invoke Start");
Console.WriteLine("");
ReturnMessage myReturnMessage = null;
if (myIMessage is IMethodCallMessage)
{
Console.WriteLine("MethodCall");
}
else if (myIMessage is IMethodReturnMessage)
Console.WriteLine("MethodReturnMessage");
if (myIMessage is IConstructionCallMessage)
{
return new ConstructionResponse(new Header[1] { new Header("__Return", this.CreateObjRef(typeof(object))) }, (IConstructionCallMessage)myIMessage);
}
myReturnMessage = new ReturnMessage(5,null,0,null,
(IMethodCallMessage)myIMessage);
Console.WriteLine("MyProxy.Invoke - Finish");
return myReturnMessage;
}
public override ObjRef CreateObjRef(Type requestedType)
{
return new MyObjRef();
}
}
class MyObjRef : ObjRef
{
public override object GetRealObject(System.Runtime.Serialization.StreamingContext context)
{
return base.GetRealObject(context);
}
}
}
I took the info from here: http://msdn.microsoft.com/en-us/library/vstudio/scx1w94y(v=vs.100).aspx
This code is supposed to work when I instance the Proxiable class:
new Proxiable() -or- Activator.CreateInstance(typeof(Proxiable))
When I instance the class the code DOES excecute -the CreateInstance in the ProxiableProxyAttribute and the Invoke method in MyProxy-. But in the Invoke method of MyProxy, I have to also emulate the constructor, and it has to return an ObjRef object. I've been trying to return this reference, but I get an exception "Invalid ObjRef provided to 'Unmarshal'."
I really don't have a clue now, this exception is very abstract, and there is little to none information about this on the internet. If anyone knows what kind of ObjRef instance the marshaller is expecting, it would really help me.
Upvotes: 2
Views: 1875
Reputation: 13217
This seems to work:
if (myIMessage is IConstructionCallMessage)
{
IConstructionReturnMessage retMsg = InitializeServerObject((IConstructionCallMessage)myIMessage);
MarshalByRefObject ret = GetUnwrappedServer();
SetStubData(this, ret);
return retMsg;
}
From MSDN Blogs.
Upvotes: 1