Hi Pascal,
You don't need to change the target at all. In fact, you're getting a
loop because the call to:
TargetMethod.Invoke(info.Target, info.Arguments);
...is causing the proxy to infinitely call itself. The proxy will
never be able to call the actual object since the DummyInterceptor
doesn't actually have an actual Adder instance that it can use to
delegate the actual call.
Try this version of the DummyInterceptor instead:
namespace LinFuFanApplication
{
public class Adder
{
public virtual int Add2(int a)
{
return a + 2;
}
}
public class DummyInterceptor : IInterceptor
{
private object _actualObject;
public DummyInterceptor(object actualObject)
{
_actualObject = actualObject;
}
public object Intercept(InvocationInfo info)
{
// Add my own custom code to the interception process
Console.WriteLine("'{0}' method called",
info.TargetMethod.Name);
// Call the actual Adder object instance instead of the
proxy;
// this will solve your looping problem
return info.TargetMethod.Invoke(_actualObject,
info.Arguments);
}
}
class Program
{
static void Main(string[] args)
{
var proxyFactory = new ProxyFactory();
var a = proxyFactory.CreateProxy<Adder>(new
DummyInterceptor(new Adder()));
var c = a.Add2(2);
}
}
..and that should do it. Go ahead and give it a try, and let me know
if it works. :)