gpt4 book ai didi

c# - 序列化/反序列化 "NHibernate Session",延迟初始化错误 ("StateServer mode"集群)

转载 作者:行者123 更新时间:2023-11-30 12:13:29 25 4
gpt4 key购买 nike

我在我的应用程序中使用了一种“每次 session session ”模式实现。在这种方法中,“NHibernate session ”保留在“HTTP session ”中。在每个“Http Request”中,“NHibernate Session”在请求开始时重新连接并在请求结束时断开连接。 “NHibernate Session”在“ session ”结束时保存在“HTTP Session”中。这工作得很好。

问题:

现在我正在考虑使用 "StateServer mode"在“Http session ”上。因此,“HTTP Session”中的所有对象都必须是可序列化的,包括“NHibernate Session”。

所以我正在进行概念验证,以验证“NHibernate Session”及其缓存对象的序列化/反序列化是否有效。

“概念验证”是以下单元测试。目标是让它通过。

代码:

/*069*/  [Test]
/*070*/ public void Test()
/*071*/ {
/*072*/ //for inspecting the SQL commands
/*073*/ NhSqlLogCapture hhSqlLogCapture = new NhSqlLogCapture();
/*074*/
/*075*/ MemoryStream ms = new MemoryStream();
/*076*/
/*077*/ ISession sessionBefore = null;
/*078*/ ISession sessionAfter = null;
/*079*/
/*080*/ //querying before the serialization.
/*081*/ try
/*082*/ {
/*083*/ sessionBefore = this.sessionFactory.OpenSession();
/*084*/ sessionBefore.FlushMode = FlushMode.Auto;
/*085*/
/*086*/ hhSqlLogCapture.Enable();
/*087*/
/*088*/ //Querying only 'DetailEtt'
/*089*/ hhSqlLogCapture.SqlStatments.Clear();
/*090*/ ICriteria crt = sessionBefore.CreateCriteria<DetailEtt>();
/*091*/ crt
/*092*/ .SetFetchMode("Master", FetchMode.Select);
/*093*/ IList<DetailEtt> cen1DetailList = crt.List<DetailEtt>();
/*094*/
/*095*/ //BEGIN: Serializing
/*096*/ //also serializing an instance of 'DetailEtt' to verify that keeps only one instance to the same database record.
/*097*/ sessionBefore.Disconnect();
/*098*/ Object[] serializationArray = new object[] { sessionBefore, sessionBefore.Get<DetailEtt>(1) };
/*099*/ BinaryFormatter bf = new BinaryFormatter();
/*100*/ bf.Serialize(ms, serializationArray);
/*101*/ //END: Serializing
/*102*/
/*103*/ //assertions
/*104*/ //Checking the sql command executed.
/*105*/ Assert.AreEqual(1, hhSqlLogCapture.SqlStatments.Count, "hhSqlLogCapture.SqlStatments.Count");
/*106*/ Regex rx = new Regex("(?is).*SELECT.*FROM.*DETAIL.*");
/*107*/ Assert.IsTrue(rx.IsMatch(hhSqlLogCapture.SqlStatments[0]), hhSqlLogCapture.SqlStatments[0]);
/*108*/
/*109*/ hhSqlLogCapture.Disable();
/*110*/ }
/*111*/ finally
/*112*/ {
/*113*/ sessionBefore = null;
/*114*/ }
/*115*/
/*116*/ try
/*117*/ {
/*118*/ //BEGIN: Deserializing
/*119*/ BinaryFormatter bf = new BinaryFormatter();
/*120*/ ms.Seek(0, SeekOrigin.Begin);
/*121*/ Object[] deserializationArray = (Object[])bf.Deserialize(ms);
/*122*/ DetailEtt dtEttDeserialized = (DetailEtt)deserializationArray[1];
/*123*/ sessionAfter = (ISession)deserializationArray[0];
/*124*/ //BEGIN: Deserializing
/*125*/
/*126*/ IDbConnection conn = this.dbProvider.CreateConnection();
/*127*/ conn.Open();
/*128*/ sessionAfter.Reconnect(conn);
/*129*/
/*130*/ //Enabling again because the session loses the reference to the log (I think).
/*131*/ hhSqlLogCapture.Enable();
/*132*/ hhSqlLogCapture.SqlStatments.Clear();
/*133*/
/*134*/ DetailEtt dtEtdSSGet = sessionAfter.Get<DetailEtt>(1);
/*135*/ MasterEtt mtEtd = dtEtdSSGet.Master;
/*136*/ Console.WriteLine(mtEtd.Description);
/*137*/
/*138*/ //assertions
/*139*/ //Checking the sql command executed.
/*140*/ Assert.AreEqual(1, hhSqlLogCapture.SqlStatments.Count, "hhSqlLogCapture.SqlStatments.Count");
/*141*/ Regex rx = new Regex("(?is).*SELECT.*FROM.*MASTER.*");
/*142*/ Assert.IsTrue(rx.IsMatch(hhSqlLogCapture.SqlStatments[0]), hhSqlLogCapture.SqlStatments[0]);
/*143*/ //verify that keeps only one instance to the same database record
/*144*/ Assert.AreSame(dtEttDeserialized, dtEtdSSGet, "verify that keeps only one instance to the same database record");
/*145*/ }
/*146*/ finally
/*147*/ {
/*148*/ sessionAfter.Close();
/*149*/ }
/*150*/ }

测试几乎通过了所有内容。但是当尝试加载一个“懒惰”的实体时它会失败。

错误:

SofPOC.Questions.SerializeSession.SerializeSessionTest.Test:
NHibernate.LazyInitializationException : Initializing[SofPOC.Questions.SerializeSession.Entities.MasterEtt#5]-Could not initialize proxy - no Session. em NHibernate.Proxy.AbstractLazyInitializer.Initialize()
at NHibernate.Proxy.AbstractLazyInitializer.Initialize()
at Spring.Data.NHibernate.Bytecode.LazyInitializer.Invoke(IMethodInvocation invocation) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data.NHibernate21\Data\NHibernate\Bytecode\LazyInitializer.cs:line 101
at Spring.Aop.Framework.AbstractMethodInvocation.Proceed() in c:\_prj\spring-net\trunk\src\Spring\Spring.Aop\Aop\Framework\AbstractMethodInvocation.cs:line 284
at Spring.Aop.Framework.DynamicProxy.AdvisedProxy.Invoke(Object proxy, Object target, Type targetType, MethodInfo targetMethod, MethodInfo proxyMethod, Object[] args, IList interceptors) in c:\_prj\spring-net\trunk\src\Spring\Spring.Aop\Aop\Framework\DynamicProxy\AdvisedProxy.cs:line 208
at DecoratorAopProxy_9872659265c04d36bc9738f2aaddfb08.get_Description()
at SofPOC.Questions.SerializeSession.SerializeSessionTest.Test() in C:\Users\hailtondecastro\lixo\stackoverflow\dotnet\StackoverflowNetPOCs_20120718\src\SofPOC.Net4.NH2.Spring13.2010\Questions\SerializeSession\SerializeSessionTest.cs:line 136

详细信息:

[Serializable]
public class DetailEtt
{
private Int32? id;
/// <summary>
/// PK
/// </summary>
public virtual Int32? Id
{
get { return id; }
set { id = value; }
}

private String description;
/// <summary>
/// TODO:
/// </summary>
public virtual String Description
{
get { return description; }
set { description = value; }
}

private MasterEtt master;
/// <summary>
/// TODO:
/// </summary>
public virtual MasterEtt Master
{
get { return master; }
set { master = value; }
}
}

MasterEtt:

[Serializable]
public class MasterEtt
{
private Int32? id;
/// <summary>
/// PK
/// </summary>
public virtual Int32? Id
{
get { return id; }
set { id = value; }
}

private String description;
/// <summary>
/// TODO:
/// </summary>
public virtual String Description
{
get { return description; }
set { description = value; }
}
}

DetailEtt.hbm.xml:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="SofPOC.Questions.SerializeSession.Entities" assembly="SofPOC.Net4.NH2.Spring13">
<class name="DetailEtt" table="DETAIL">
<id name="Id" type="Int32">
<column name="ID" sql-type="INTEGER"></column>
<generator class="assigned"></generator>
</id>
<property name="Description" type="String">
<column name="DESCRIPTION" sql-type="VARCHAR( 100 )"></column>
</property>
<many-to-one name="Master" fetch="select">
<column name="MS_ID" sql-type="INTEGER"></column>
</many-to-one>
</class>
</hibernate-mapping>

MasterEtt.hbm.xml:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="SofPOC.Questions.SerializeSession.Entities" assembly="SofPOC.Net4.NH2.Spring13">
<class name="MasterEtt" table="MASTER">
<id name="Id" type="Int32">
<column name="ID" sql-type="INTEGER"></column>
<generator class="assigned"></generator>
</id>
<property name="Description" type="String">
<column name="DESCRIPTION" sql-type="VARCHAR( 100 )"></column>
</property>
</class>
</hibernate-mapping>

问题:

即使在重新连接反序列化的“Hibernate Session”后,我也会收到“Lazy Load Error”。如何在不必重新附加实体的情况下避免这种“延迟加载错误”?

我正在使用:

  • Spring.Net 1.3.2
  • NHibernate 2.1.2
  • System.Data.SQLite 1.0.80.0

完整的来源在这里:Q11553780.7z

注意事项:

  • 在打开解决方案(“.\Src\SofPOC.2010.sln”)之前运行“.\Dependencies\setup.bat”以加载依赖项。
  • 有关依赖项的说明,请参阅“.\readme.txt”和“.\dependencies\readme.txt”。

已编辑:

我发现问题的原因出在NHibernate的NHibernate.Proxy.AbstractLazyInitializer类中。字段 _session 标记为 [NonSerialized]。这使得该字段不被序列化。因此它在反序列化后为 null。

查看代码:

namespace NHibernate.Proxy
{
[Serializable]
public abstract class AbstractLazyInitializer : ILazyInitializer
{
/// <summary>
/// If this is returned by Invoke then the subclass needs to Invoke the
/// method call against the object that is being proxied.
/// </summary>
protected static readonly object InvokeImplementation = new object();

private object _target = null;
private bool initialized;
private object _id;
[NonSerialized]
private ISessionImplementor _session;
...

编辑 2:

问题的原因实际上是 [NonSerialized] 属性,因为当我进行以下“hack”时,测试通过了。通过反射(reflection),我将“_session”的属性从“Private | NotSerialized”更改为仅“Private”。

黑客:

    protected override void OnSetUp()
{
//Hacking "_session"
Type aliType = Type.GetType("NHibernate.Proxy.AbstractLazyInitializer, NHibernate");
FieldInfo fiSession = aliType.GetField("_session", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
FieldInfo fi_m_fieldAttributes =
fiSession.GetType().GetField(
"m_fieldAttributes",
System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance);
// changing it from "Private | NotSerialized" to only "Private"
fi_m_fieldAttributes.SetValue(fiSession, FieldAttributes.Private);

base.OnSetUp();
}

最佳答案

据我所知,可以尝试三种选择:

  1. 使用反射设置反序列化 session 的_session字段
  2. 打开一个新 session 并重新连接它们。这样做可能会很痛苦,但我认为,如果 NHibernate 团队让做某事变得困难,他们可能有充分的理由。
  3. 创建您自己的 ILazyInitializer。 ServerSide有一篇文章讲过here .我自己还没有尝试过。

如果您尝试 nr 1,请告诉我们它是否有效。我很想看看会发生什么。理论上它应该有效。

关于c# - 序列化/反序列化 "NHibernate Session",延迟初始化错误 ("StateServer mode"集群),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11553780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com