First level cache in Castle ActiveRecord

While I was trying to use first level cache in a Castle ActiveRecord based application I found some points that like to share:

1. First level cache is alive within a single session (NHibernate’s ISession) only.

2. First level cache is enabled by default and can not be disabled.

3. If you don’t use SessionScope properly you may have more than one session per ASP.NET web request. So you will not profit from first level cache. SessionScope is Castle ActiveRecord’s way for NHibernate’s ISession. Correct way to use SessionScopt in an ASP.NET web application is to use SessionScopeWebModule as a httpModule. More info could be found here.

4. First level cache can be used only by NHibernate Load and Get methods. So with Castle ActiveRecord you can only use Find and TryFind method. FindAll and other methods can not benefit from first level cache because they use ICriteria internally.

More info about NHibernate caching is available here.

Access NHibernate.ISession from Castle ActiveRecord

If you are a Castle ActiveRecord user you may currently encountered situations that it is needed to do some specific operation that is possible just via NHibernate or even just need to direct access to NHibernate’s ISession. For example if you want to use LINQ-to-NHibernate or run SQL query with Castle ActiveRecord, there is no way other than direct access to ISession.

To access NHibernate’s ISession you must utilize ActiveRecordMediator.Execute() or ActiveRecordBase.Execute(). This method accepts a NHibernateDelegate delegate. Then through this delegate you have access to NHibernate’s ISession. Consider following code that uses LINQ-to-NHibernate through Castle ActiveRecord:

[ActiveRecord(Lazy = true)]
public class Car: ActiveRecordBase
public static List GetCars()
return (List)Execute(
delegate(ISession session, object instance)
//here you have direct access to ISession

var q = from car in session.Linq()
select car;

return q.ToList();
}, null);

For more examples go to this, this and this link.