Castle DynamicProxy: Get unproxied object

前端 未结 4 1017
旧时难觅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:24

    If you don't have an invocation object available, or if you observe 'Castle.Proxies.IXeroServiceProxy.__target' is inaccessible due to its protection level when trying @s1mm0t's answer, you can try the following code which uses reflection instead of dynamic:

    public static T UnwrapProxy(T proxy) {
       if(!ProxyUtil.IsProxy(proxy)) {
          return proxy;
       }
       try {
          const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance;
          var proxyType = proxy.GetType();
          var instanceField = proxyType.GetField("__target", flags);
          var fieldValue = instanceField.GetValue(proxy);
          return (T) fieldValue;
       }
       catch(RuntimeBinderException) {
          return proxy;
       }
    }
    

提交回复
热议问题