Castle动态代理对象到原始对象的转换

时间:2014-10-18 18:00:07

标签: c# castle castle-dynamicproxy dynamic-proxy

 ProxyGenerator generator = new ProxyGenerator();
 var interceptor = new StandardInterceptor();
 MyInterfaceImpl test = (MyInterfaceImpl)generator.CreateClassProxy(typeof(MyInterfaceImpl), interceptor);

在上面的示例中,test对象是代理对象,假设它是由第三方创建的。

我无法传递接受MyInterfaceImpl参数的WCF操作合同,因为其类型不是MyInterfaceImpl,而是MyInterfaceImplProxy

我们如何将test对象转换为MyInterfaceImpl类型?请帮忙。

2 个答案:

答案 0 :(得分:2)

我找到了这个答案here

internal static TType UnwrapProxy<TType>(TType proxy)
{
    if (!ProxyUtil.IsProxy(proxy))
        return proxy;

    try
    {
        dynamic dynamicProxy = proxy;
        return dynamicProxy.__target;
    }
    catch (RuntimeBinderException)
    {
        return proxy;
    }
}

答案 1 :(得分:1)