I use in my application a kind of "session-per-conversation" pattern implementation.
In this approach the "NHibernate Session" is kept on the "HTTP Session". In every "Http Request" the "NHibernate Session" is reconnected at the beginning and disconnected at the end of the request. The "NHibernate Session" is kept in "HTTP Session" by the end of the "conversation". This is working very well.

The Problem:

Now I'm considering using "StateServer mode" on the "Http Session".
Thus, all objects in the "HTTP Session" must be serializable, including the "NHibernate Session".

So I'm doing a proof of concept to validate that the serialization/deserialization of a "NHibernate Session" and its cached objects works.

The "proof of concept" is the following unit test. And the goal is to make it pass.

Before opening the solution (".\ Src\SofPOC.2010.sln") run ".\Dependencies\setup.bat" to load dependencies.

See ".\readme.txt" and ".\dependencies\readme.txt" for instructions about the dependencies.

EDITED:

I found that the cause of the problem is in the class NHibernate.Proxy.AbstractLazyInitializer of NHibernate. The field _session is marked as [NonSerialized]. This makes this field not be serialized. Consequently it is null after deserialization.

The cause of the problem is really the attribute [NonSerialized] because when I make the following "hack" the test passes. By Reflection, I make a change on the attributes of the "_session" from "Private | NotSerialized" to only "Private".

thanks for the help. I want to test the three options. I have a consideration to do: aboult "...even if it wasn't marked NonSerializable.". I think you are mistaken at that point. Using reflection I made a hack in the FieldInfo of "_session" changing it from "Private | NotSerialized" to only "Private". And it worked.
–
HailtonJul 25 '12 at 21:40

the third solution seems more attractive. The first solution seems a little impractical because I would have to identify instances that are "dynamic proxies", but I agree it works. The second solution is exactly what I want to avoid, that's why I'm using the "session-per-conversation" pattern.
–
HailtonJul 26 '12 at 0:17

1

Now that I read my answer again in daylight, "If you deserialize a session, it doesn't magically appear in that _session field (even if it wasn't marked NonSerializable).' doesn't make any sense so I removed it from the answer.
–
JeroenJul 30 '12 at 13:51