Dashboard > ActiveRecord > ... > Documentation > Scopes
Scopes
Added by Daniel Rothmaler, last edited by Daniel Rothmaler on Aug 20, 2007
Labels: 
(None)


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

Site running on a free Atlassian Confluence Community License granted to Castle Project. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.4 Build:#809 Jun 12, 2007) - Bug/feature request - Contact Administrators