Scopes
Scopes allow you to optimize or add some semantic to a code block.
Session Scope
Session scope allows you to reuse the NHibernate session, thus not flushing it after each database operation. This can dramatically improve the performance on database intense methods.
using(new SessionScope()) { Blog blog = new Blog(); blog.Author = "hammett"; blog.Name = "some name"; blog.Save(); Post post = new Post(blog, "title", "post contents", "Castle"); post.Save(); }
Transaction Scope
To enable transaction we also provide a scope:
TransactionScope transaction = new TransactionScope(); try { Blog blog = new Blog(); blog.Author = "hammett"; blog.Name = "some name"; blog.Save(); Post post = new Post(blog, "title", "post contents", "Castle"); post.Save(); } catch(Exception) { transaction.VoteRollBack(); throw; } finally { transaction.Dispose(); }
Nested transactions
You can also have nested transaction, that are particularly usefull when you have a layer to mark transaction boundaries:
using(TransactionScope root = new TransactionScope()) { Blog blog = new Blog(); using(TransactionScope t1 = new TransactionScope(TransactionMode.Inherits)) { blog.Author = "hammett"; blog.Name = "some name"; blog.Save(); t1.VoteCommit(); } using(TransactionScope t2 = new TransactionScope(TransactionMode.Inherits)) { Post post = new Post(blog, "title", "post contents", "Castle"); try { post.SaveWithException(); } catch(Exception) { t2.VoteRollBack(); } } }
Note the TransactionMode.Inherits
