Sunday, April 10, 2011

Boilerplate code for Fluent NHibernate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Cfg;
using FluentNHibernate.Conventions.Helpers;

namespace FnhNavigationTesting
{
    public static class SessionFactoryBuilder
    {
        static ISessionFactory _sf = null;
        public static ISessionFactory GetSessionFactory()
        {
            // Building SessionFactory is costly, should be done only once, making the backing variable static shall prevent creation of multiple factory
            try
            {
                if (_sf != null) return _sf;

                _sf = 
                    Fluently.Configure()
                    .Database(
                        MsSqlConfiguration.MsSql2008
                        .ConnectionString(
                            @"Data Source=localhost;Initial Catalog=OkSystem;User id=sa;Password=opensesame"))
                    .Mappings( x => x.FluentMappings.AddFromAssemblyOf<Program>())
                    .BuildSessionFactory();

                return _sf;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.InnerException.Message + "\n" + ex.InnerException.StackTrace);
            }
        }
    }//SessionFactoryBuilder
}

No comments:

Post a Comment