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