Take the 2-minute tour ×

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)));

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

The problem with a cached object is it gets disconnected with the current session.

With a web session-per-request model this is going to be an issue.

You need to reattach the detached cached object to the current session:

session.Lock(cachedObject, LockMode.None);

But this throws up potential concurrency issues if cachedObject is writable elsewhere in the app. I would suggest the cache is for readonly data and when you need to persist something, its nearly always the best apparoach to fetch it fresh as you are doing.

share|improve this answer
Thanks, that knowledge helps me understand why it is doing what it is doing, however, does not effectively solve the issue. Perhaps the best option is to not cache and to utilize lazy loading by itself. –  Anthony Mason Jun 16 '13 at 15:59

Your Answer


