I am trying to understand Castle's DynamicProxy and the thing I would like to do is to change the target of the generated proxy at runtime.
Something like this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;
namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
IFoo foo = new Foo("Foo 1");
IFoo foo2 = new Foo("Foo 2");
foo.DoSomething("Hello!");
ProxyGenerator generator = new ProxyGenerator();
IFoo proxiedFoo = generator.CreateInterfaceProxyWithTarget<IFoo>(foo);
proxiedFoo.DoSomething("Hello proxied!");
(proxiedFoo as IChangeProxyTarget).ChangeProxyTarget(foo2); // cast results in null reference
proxiedFoo.DoSomething("Hello!");
}
}
}
I thought the generated proxy would implement IChangeProxyTarget
but the cast to the interface results in a null reference.
How can I change the target of a generated proxy at runtime?
Update As mentioned in an answer, I tried using CreateInterfaceProxyWithTargetInterface
and I'm still unable to cast to IChangeProxyTarget to change the target.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.DynamicProxy;
namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
IFoo foo = new Foo("Foo 1");
IFoo foo2 = new Foo("Foo 2");
foo.DoSomething("Hello!");
ProxyGenerator generator = new ProxyGenerator();
IFoo proxiedFoo = generator.CreateInterfaceProxyWithTargetInterface<IFoo>(foo);
proxiedFoo.DoSomething("Hello proxied!");
IChangeProxyTarget changeProxyTarget = proxiedFoo as IChangeProxyTarget;
if (changeProxyTarget == null) // always null...
{
Console.WriteLine("Failed");
return;
}
changeProxyTarget.ChangeProxyTarget(foo2);
proxiedFoo.DoSomething("Hello!");
}
}
}
use CreateInterfaceProxyWithTargetInterface
That one will allow you to change the proxy/invocation target.
Also the IChangeProxyTarget
is implemented by invocation type, not the proxy itself.