News


In my previous post I have used a OperationsInTransaction.Execute() method. This is my simple wrapper for the NHibernate ISession and ITransaction method.

Normally when we want to execute some query in the transaction we must write this piece of code

using (ISession session = SessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    try
                    {
                        //some query 
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }

Unfortunatelly we must write it every time when we want to execute some query on the database. Following the DRY principle I have created mini wrapper for it:

 public static class OperationsInTransaction
    {
        private static ISessionFactory sessionFactory;
        private static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    sessionFactory = new NhibernateConfig().CreateFactory();
                }

                return sessionFactory;
            }
        }

        public static void Execute(IsolationLevel level, Action<ISession> operations)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction(level))
                {
                    try
                    {
                        operations(session);
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw;
                    }
                }
            }
        }

        public static void Execute(Action<ISession> operations)
        {
            Execute(IsolationLevel.ReadCommitted, operations);
        }
    }

In this piece of code I'm creating every time in the background the new ISession and ITransaction objects when I'm execute some queries.

With this wrapper, what I need to write is only:

            OperationsInTransaction.Execute(session =>
            {
                var element = new SetAvailableExtensionsList().Execute(session, serializedExtensions);
                session.Save(element);
            });

Comments have been closed on this topic.