1

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!");
        }
    }
}
4

1 に答える 1

1

使用するCreateInterfaceProxyWithTargetInterface

これにより、プロキシ/呼び出しターゲットを変更できます。

また、IChangeProxyTargetプロキシ自体ではなく、呼び出しタイプによって実装されます。

于 2013-07-31T10:30:18.500 に答える