Castle DynamicProxy: Get unproxied object

前端 未结 4 1025
旧时难觅i
旧时难觅i 2020-12-06 18:44

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 s

4条回答
  •  青春惊慌失措
    2020-12-06 19:25

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

提交回复
热议问题