I have been experiencing some major caching and lazy loading problems with NHibernate using C# and ASP.NET. It was not until we enabled caching that this begun. In many situations we have to write code to null out an object and to a fresh get in order to preserve the wanted properties, otherwise documents are generated with invalid information or objects are saved and overwrite the most current data.
Other times, lazy loading has fails to fetch data and throws an exception. In these cases it is always an object with a one to many relationship. So we have and object with an IList property and when we hit a foreach loop, it throws an exception stating that it could not lazily load the collection. In these cases we simply do a getById of the object and instantiate a new object.
Below is the psuedo-code for a couple work arounds I have resorted to using. These work in most cases, however, I should not have to be writing this extra code.
for threaded applications:
Thread thread = new Thread(new ThreadStart(() => GetObjectNotFromCache(objectGuid, out object)));
thread.Start();
thread.Join();
private static void GetObjectNotFromCache(Guid objectId, out Object object)
{
var db = new db() // auto generated file that handles CRUD operations
object= db.GetObjectById(objectId);
}
for web app:
var db = new db();
object = db.GetObjectById(objectId);
object = null;
object = db.GetObjectById(objectId);
Our Session Manager enables caching by the following:
public static ISession OpenSession()
{
ISession session;
if (CurrentSessionContext.HasBind(GetFactory()))
{
session = GetFactory().GetCurrentSession();
}
return session
}
These hacks are allowing us to continue development, however, they slow us down tremendously. Can anyone help identify where this problem may be happening? One more thing to note is that on save of an object we evict the current session. This was added to prevent the cache from persisting after an update. This did help the problem but did not solve it.