如何使用Castle DynamicProxy更改目标

时间:2013-07-29 14:47:14

标签: c# castle-dynamicproxy

我想了解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!");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用CreateInterfaceProxyWithTargetInterface

允许您更改代理/调用目标。

IChangeProxyTarget也是由调用类型实现的,而不是代理本身。