Using Castle ActiveRecord, I stumbled into a problem when lazy-loading.
The following works (obviously)
using (new SessionScope())
{
User singleUser = User.FindFirst(...)
UserGroup groups = singleUser.Groups; // Lazy-loading groups.
}
Since I need to modify the session filters in a certain context (using interceptors), I create a new SessionScope.
using (new SessionScope())
{
User singleUser;
EnableVariousFiltersInThisThread();
using (new SessionScope())
{
singleUser = User.FindFirst(...);
}
DisableVariousFiltersInThisThread();
UserGroup groups = singleUser.Groups; // Lazy-loading groups.
}
The last line "singleUser.Groups" throws a LazyInitializationException: "failed to lazily initialize a collection of role: Groups, no session or session was closed".
However, all other session operations work correctly. So it seems that "singleUser" is bound to the now disposed SessionScope. Why? And how can this be solved alternatively?
My GUESS is - part of the reason is about "Identity Map". Not only lazy loaded objects, but also all objects are bound to a session. This makes sure no two objects represent a single row in database.