Castle の DynamicProxy を理解しようとしていますが、実行時に生成されたプロキシのターゲットを変更したいと考えています。
このようなもの...
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!");
}
}
}
生成されたプロキシが実装されると思ってIChangeProxyTarget
いましたが、インターフェイスへのキャストにより null 参照が発生します。
実行時に生成されたプロキシのターゲットを変更するにはどうすればよいですか?
更新回答で述べたように、使用してみCreateInterfaceProxyWithTargetInterface
ましたが、IChangeProxyTarget にキャストしてターゲットを変更することはまだできません。
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!");
}
}
}