识别 NHibernate 代理类 [英] Identifying NHibernate proxy classes

查看:21
本文介绍了识别 NHibernate 代理类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不是 NHibernate 用户;我编写了一个序列化实用程序库.用户记录了一个特性请求,我应该处理 NHibernate 代理类,将它们视为实际类型.目前我的代码将它们视为意外的继承,并抛出异常.

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 same as the actual type. At the moment my code is treating them as unexpected inheritance, and throwing an exception.

代码不会提前知道NHibernate(包括没有参考,但我不担心反射;-p)

The code won't know in advance about NHibernate (including no reference, but I'm not aftaid of reflection ;-p)

是否有一种可靠的/有保证的方法来检测此类代理类型?显然 DataContractSerializer 处理得很好,所以我希望它很简单.也许是一些界面或[attribute]装饰.

Is there a robust / guaranteed way of detecting such proxy types? Apparently DataContractSerializer handles this fine, so I'm hoping it is something pretty simple. Perhaps some interface or [attribute] decoration.

此外,在反序列化过程中;目前我将创建原始类型(不是 NHibernate 类型).这对于持久性目的是否合适?还是需要代理类型?如果是后者;创建代理类型的实例需要什么?

Also, during deserialization; at the moment I would be creating the original type (not the NHibernate type). Is this fine for persistence purposes? Or is the proxy type required? If the latter; what is required to create an instance of the proxy type?

推荐答案

您可以通过将类强制转换为(不出所料)INHibernateProxy 来检测类是否是 NHibernate 代理.

You can detect if a class is a NHibernate proxy by casting it to (unsurprisingly) INHibernateProxy.

如果需要获取底层的真实"对象,请使用:

If you need to get the underlying "real" object, use:

Session.GetSessionImplementation().PersistenceContext.Unproxy(proxiedObject)

您不需要测试代理来调用Unproxy;如果不是代理,则返回原始参数.

You don't need to test for proxies to call Unproxy; it returns the original parameter if it's not a proxy.

我现在使用不同的方法来获取底层对象,主要是为了解决延迟加载和继承问题:http://sessionfactory.blogspot.com/2010/08/hacking-lazy-loaded-inheritance.html

I now use a different approach to get the underlying object, mostly to work around lazy loading and inheritance: http://sessionfactory.blogspot.com/2010/08/hacking-lazy-loaded-inheritance.html

这篇关于识别 NHibernate 代理类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆