Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

.net - Castle DynamicProxy: Get unproxied object

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).

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);

is always true.

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

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

with the same results, realInstance is still a proxy.

What am I missing here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...