城堡DynamicProxy:非代理获取对象城堡、对象、DynamicProxy

2023-09-03 01:33:28 作者:江南春失忆梦

我用城堡DynamicProxy一个拦截器添加到我的类型。 现在,我需要的底层基本类型(而不是代理本身)。

I'm using Castle DynamicProxy to add an interceptor to my types. Now I need to get the underlying base type (NOT the proxy itself).

我发现这么几个提示,建议使用这样的ProxyUtil类:

I found a few hints on SO that suggested to use the ProxyUtil class like this:

object realInstance = ProxyUtil.GetUnproxiedInstance(proxyInstance);

似乎这不能按

This does not seem to work as

bool isProxy = ProxyUtil.IsProxy(realInstance);

始终为真。

我也尝试使用以下code段,基本上是什么ProxyUtil是这样做的:

I also tried using the following code snippet, which is essentially what ProxyUtil is doing:

var accessor = proxyInstance as IProxyTargetAccessor;
var realInstance = accessor.DynProxyGetTarget();

具有相同的结果,realInstance仍然是一个代理服务器。

with the same results, realInstance is still a proxy.

我是什么在这里失踪?

推荐答案

这个问题是有点老了,但希望我的解决方案(依赖于.NET 4+)会帮助别人。

This question is a little old but hopefully my solution (which relies on .NET 4+) will help someone.

说完如下创建一个代理:

Having created a proxy as follows:

ProxyGenerator generator = new ProxyGenerator();
MyClass proxy = generator.CreateClassProxyWithTarget(underlying, new MyInterceptor(this));

我已经能够得到基本目标与下面的方法:

I have been able to get the underlying target with the following method:

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

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

它依赖于城堡的内部实现 - 即该生成的代理有__target成员。这是很好的和自包含的,虽然和备份的单元测试或两个,我们应该抓住任何变动应城堡更高版本打破这一点。这是使用城堡v3.2.0.0。

It relies on the internal implementation of Castle - i.e. that the generated proxy has a __target member. It is nice and self contained though and backed up with a unit test or two, we should catch any changes should a later version of Castle break this. This is using v3.2.0.0 of Castle.