【发布时间】:2011-04-08 10:30:02
【问题描述】:
我正在尝试使用 WCF 通过线路发送 NH 实体。我有一个复杂的延迟加载对象图.. 我尝试实现自定义 DataContractSurrogate 以在序列化时强制初始化。 这是代码:
public class HibernateDataContractSurrogate : IDataContractSurrogate
{
public HibernateDataContractSurrogate()
{
}
public Type GetDataContractType(Type type)
{
// Serialize proxies as the base type
if (typeof(INHibernateProxy).IsAssignableFrom(type))
{
type = type.GetType().BaseType;
}
// Serialize persistent collections as the collection interface type
if (typeof(IPersistentCollection).IsAssignableFrom(type))
{
foreach (Type collInterface in type.GetInterfaces())
{
if (collInterface.IsGenericType)
{
type = collInterface;
break;
}
else if (!collInterface.Equals(typeof(IPersistentCollection)))
{
type = collInterface;
}
}
}
return type;
}
public object GetObjectToSerialize(object obj, Type targetType)
{
if (obj is INHibernateProxy)
{
obj = ((INHibernateProxy)obj).HibernateLazyInitializer.GetImplementation();
}
// Serialize persistent collections as the collection interface type
if (obj is IPersistentCollection)
{
IPersistentCollection persistentCollection = (IPersistentCollection)obj;
persistentCollection.ForceInitialization();
obj = persistentCollection.Entries(null); // This returns the "wrapped" collection
}
return obj;
}
public object GetDeserializedObject(object obj, Type targetType)
{
return obj;
}
public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
{
return null;
}
public object GetCustomDataToExport(Type clrType, Type dataContractType)
{
return null;
}
public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
{
}
public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
{
return null;
}
public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
{
return typeDeclaration;
}
}
但是,我不断收到异常:
NHibernate.Exceptions.GenericADOException: could not initialize a collection [SQL trace] ---> System.ObjectDisposedException: Session is closed!
查看堆栈跟踪,似乎这一行persistentCollection.ForceInitialization();
正在抛出异常。
我能做什么?
PS:我想使用 DTO 而不是序列化复杂的 NH 实体,但是这里不可能。
【问题讨论】:
-
请问你为什么使用延迟加载?
标签: c# wcf nhibernate serialization lazy-loading