Wednesday, January 20, 2010

NHibernate: Is That Type a Proxy?

One of our applications does some reflection to map customizable content to domain objects. Anyone familiar with NHibernate and lazy loading has probably encountered proxy classes before. My problem: given a Type, I want the domain type.

It's easy to find out that proxy types extend the domain type they represent, so if I know that my Type is a proxy I can call BaseType to get the domain type. But how do I know if my Type is a proxy?

I tried numerous approaches, but the simplest I found was to look for a specific interface. Turns out proxies implement an interface called INHibernateProxy.

if (clazz.GetInterface(typeof(INHibernateProxy).FullName) != null)
clazz = clazz.BaseType;

Now clazz represents the domain type as desired.

There are other solutions of course, such as detecting the namespace (proxies have none), and possibly checking IsAutoClass (which I couldn't confirm in any documentation). This approach seems the most reliable.

No comments: