问题描述
我不是一个NHibernate的用户;我写了一个序列化工具库。用户登录功能请求,我应该处理NHibernate的代理类,对待他们一样的实际类型。此刻我的code被他们当作意外的继承,并抛出异常。
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.
在code不会事先知道NHibernate的(包括未提及,但我不aftaid反射;-p的)
The code won't know in advance about NHibernate (including no reference, but I'm not aftaid of reflection ;-p)
有一个强大的/担保方式检测这些代理类型?显然的DataContractSerializer
处理这很好,所以我希望它是值得pretty的简单。或许有些接口或 [属性]
装修。
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?
推荐答案
您可以检测,如果一个类是NHibernate的代理通过其铸造(意料之中) INHibernateProxy
。
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的代理类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!