What is the difference between StatelessSession and Session in NHibernate?

Stateless session is not tracking entities that are retrieved. For example for regular ISession following code:

var session = sessionFactory.OpenSession()
using(var transaction = session.BeginTransaction()){
    var user = session.Get<User>(1);
    user.Name = "changed name";
    transaction.Commit();
}

will result in update in DB. This tracking consumes memory and makes ISession performance to degrade over time since amount of tracked entities is growing.

The same code with IStatelessSession won’t do anything. Stateless sessions are used when you need to load lots of data and perform some batching operations. It can be used to work with large data sets in a more “ado.net” style.

Leave a Comment