Hello,
I want to be able to call methods of a type A (which implements interface
IA) on an object which is of type B (and implements interface IB). I have a
table that mapps every method of type IA to its corresponding method in type
IB.
The method that I want to call is this one:
public int a1(IA pa, int recursionNb)
{
if (recursionNb <= 0) return 1;
else return pa.a1(pa, recursionNb - 1);
}
(The method that corresponds in IB is exactly the same, but IA is replaced
by IB)
To do this I use a proxy:
public class DynamicProxy : RealProxy
{
private object targetObj = null;
private Type proxyType = null;
public DynamicProxy(Type t, object o) : base(t)
{
proxyType = t; //type IA
targetObject = o; //object of type B on which the method will be
called
}
public override IMessage Invoke(IMessage msg)
{
IMethodMessage m = (IMethodMessage)msg;
//In m, I can find the method that has been called with its
parameters (a1).
//I get the MethodInfo mi of the corresponding method (b1)
//However, I cannot call mi.Invoke(targetObject, {pa, recursionNb})
since pa is of type A.
//Thus I create a DynamicProxy:
DynamicProxy dp = new DynamicProxy(typeof(IB), pa);
object tProxy = dp.GetTransparentProxy();
object[] params = {tProxy, recursionNb};
int res = mi.Invoke(targetObject, params);
return new IMessage(res, null, 0, m.LogicalCallContext,
(IMethodCallMessage)m);
}
}
Then in the main method, I have:
DynamicProxy dProxy = new DynamicProxy(typeof(IA), objB); //objB is an
object of type B
IA transProxy = (IA)dProxy.GetTransparentProxy();
int i = transProxy.a1(new A(), 10);
There is a problem when the targetObject is a __TransparentProxy (that is
recursionNb >= 2). The problems happens when calling Invoke on the
MethodInfo, with the __TransparentProxy as a parameter.
No exception is thrown, but no method is called. Even with the debugger I
cannot step into mi.Invoke(targetObject, param), when targetObject is of
type __TransparentProxy.
I don't understand, why this is not possible.
Thanks
Valéry