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,但对接口的强制转换会导致空引用。

如何在运行时更改生成的代理的目标?

更新如答案中所述,我尝试使用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 回答