如何使用Castle DynamicProxy更改目标

本文关键字:目标 DynamicProxy 何使用 Castle | 更新日期: 2023-09-27 18:25:18

我正在尝试理解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!");
        }
    }
}

如何使用Castle DynamicProxy更改目标

使用CreateInterfaceProxyWithTargetInterface

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

此外,IChangeProxyTarget是通过调用类型实现的,而不是代理本身。