I\'m not an NHibernate user; I write a serialization utility library. A user has logged a feature-request that I should handle NHibernate proxy classes, treating them the sa
Diego's method fully loads the object before attempting to determine it's type - this is definitely the most generic approach, but you may not need to load the object if the concrete type is already known to the Proxy.
Vijay's method is faster in cases where the concrete type is known in advance - but as pointed out by Diego, in some cases, that information is not available, because the information required to determine the exact type has not yet been loaded.
Taking both scenarios into account, I came up with the following:
https://gist.github.com/1089489
The interesting piece is this:
if (entity is INHibernateProxy)
{
var lazyInitialiser = ((INHibernateProxy)entity).HibernateLazyInitializer;
var type = lazyInitialiser.PersistentClass;
if (type.IsAbstract || type.GetNestedTypes().Length > 0)
return Service.Session.GetSessionImplementation().PersistenceContext.Unproxy(entity).GetType();
else // we don't need to "unbox" the Proxy-object to get the type
return lazyInitialiser.PersistentClass;
}
return entity.GetType();
This checks first to see if the type behind the Proxy is abstract, and uses Vijay's or Diego's method, depending on whether the concrete type is known.
In other words, it only loads the object if the type behind the Proxy is not a concrete type, or may be of a sub-type.
I did a quick unit test to demonstrate that this works, but I don't imagine I've tested all possible cases - I believe the idea is sound, but I would like to hear comments from Diego and Vijay, or others.
Thanks!
EDIT: Posted an update to the gist above, with an additional generic method that can be used to Unproxy() an Entity - there are some cases where you may have to do that...