NHibernate - Sessão

Em NHibernate eu uso a singleton pattern para implementar uma classe que me faça a gestão da sessão. 
Este é um exemplo de como essa classe costuma ser:

public class SessionProvider
    {
        private SessionProvider()
        {
        }

        public static SessionProvider Instance { get; private set; }
        private static ISessionFactory sessionFactory;
        static SessionProvider()
        {
            var provider = new SessionProvider();
            provider.Initialize();
            Instance = provider;
        }
        private const string ConnectionString = "Server=localhost;Port=3307;user=root;Password=123;Database=Exemplo";
        private void Initialize()
        {
            var configuration = Fluently.Configure()
            .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                          .ConnectionString(ConnectionString).ShowSql()
            )
            .Mappings(m =>
                      m.FluentMappings
                          .AddFromAssemblyOf<Core.Domain.Property>()
                          .AddFromAssemblyOf<Core.Domain.PropertySubscription>())
            .ExposeConfiguration(cfg => new SchemaExport(cfg)).BuildConfiguration();
            sessionFactory = configuration.BuildSessionFactory();
        }
        public static void GenerateDatabase()
        {
            var configuration = Fluently.Configure()
            .Database(FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                          .ConnectionString(ConnectionString).ShowSql()
            )
            .Mappings(m =>
                      m.FluentMappings
                          .AddFromAssemblyOf<Core.Domain.Property>()
                          .AddFromAssemblyOf<Core.Domain.PropertySubscription>())
            .ExposeConfiguration(cfg => new SchemaExport(cfg)).BuildConfiguration();
            var exporter = new SchemaExport(configuration);
            exporter.Execute(true, true, false);
        }
        public ISession OpenSession()
        {
            return sessionFactory.OpenSession();
        }
    }

Esta é uma forma de como lido com a sessão.

using(var session = SessionProvider.Instance.OpenSession())
using (var transaction = session.BeginTransaction())
{
    try
    {
        transaction.Commit();
    }
    catch (Exception e)
    {
        transaction.Rollback();
        throw;
    }
    finally
    {
        session.Close();
    }
}
Published 11-12-2011 5:07 por Guilherme Cardoso
Filed under: ,

Leave a Comment

(requerido) 
(requerido) 
 
(opcional)
(requerido) 
If you can't read this number refresh your screen
Enter the numbers above: