Wednesday, July 22, 2009

How to get type masked by Castle Dynamic Proxy

Hello there, back from my vacation.

When writing "ORM" for Sharepoint lists I've encountered a problem with Castle Dynamic Proxy. I had to get the type which was wrapped with proxy and had no way to get that type in any other way besides getting it from the proxy itself.
Here's a little hack that does that through reflection:
var objProxy = obj as IProxyTargetAccessor;
if (objProxy != null)
{
var proxyTargetType= (Type)objProxy.GetType().GetField("typeTokenCache").GetValue(objProxy);
}
Note, however, that implementation of Dynamic Proxy might change and this hack will stop working then.

P.S. If anybody knows how to do it in a "right" way, post please.

2 comments:

  1. There's no universal way of doing this, because 'type masked by DP' is vague. You can have an interface proxy that implements multiple interfaces. Which one would you consider as the one being masked? For class proxy, it's the base type, but again, you can implement interfaces and proxy calls to them as well. For proxies with target, you can have multiple targets aka mixins. What would that mean in your scenario?

    I don't think there's a good answer to yor question in general. You may answer it specifically in your constrained environment, (like when you only ever ever can have class proxies) but that's it.

    ReplyDelete
  2. Krzysztof Koźmic, thanks alot for a comment. Sounds reasonable.

    ReplyDelete