EPiServer  /  Relate July 22, 2009

Leaner EPiServer Community factory methods with RunInTransaction()

A few months ago I published a series of articles on EPiServer World about how to build a custom EPiServer Community module. In it I described a method using try-catch for handling database transactions in the factory methods. Like this:

internal static Movie AddMovie(Movie movie)
{
    bool wasInTransaction = DatabaseHandler.InTransaction;
    if (!wasInTransaction)
        DatabaseHandler.BeginTransaction();

    int newId = -1;
    try
    {
        //Actually do some useful stuff
        //like saving the movie to the database

        if (!wasInTransaction)
            DatabaseHandler.Commit();
    }
    catch (Exception)
    {
        if (!wasInTransaction)
            DatabaseHandler.Rollback();
        throw;
    }

    return MovieHandler.GetMovie(newId);
}

Notice how we have to jump through some hoops to handle creating a transaction, rolling back the transaction if something goes wrong etc. Since we have to do this exact same procedure each time we add, update or remove an entity it will clutter up our code in our factory quite a lot. Luckily there is a very simple solution provided by the Community platform which I unfortunately didn’t know about when I wrote the articles but was pointed out to me later by Mattias Nordberg.

The DatabaseHandler class has a RunInTransaction method which accepts a delegate as parameter and then does the exact same thing as above for us, invoking the delegate at the point where I inserted a comment in the code above. Using this method we can rewrite the above code to this:

internal static Movie AddMovie(Movie movie)
{
    int newId = -1;
    DatabaseHandler.RunInTransaction(() =>
     {
         //Actually do some useful stuff
         //like saving the movie to the database
     });

    return MovieHandler.GetMovie(newId);
}

With this approach we save quite a few lines of code making our factory methods less error prone and much more readable.

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more

Comments

comments powered by Disqus

My book

Want a structured way to learn EPiServer 7 development? Check out my book on Leanpub!

More about EPiServer Relate