views:

350

answers:

1

Hi,

I'm new to NHibernate...

I have been following this NHibernate Tutorial from Gabriel Schenker : http://nhforge.org/wikis/howtonh/your-first-nhibernate-based-application.aspx

However, this tutorial uses hbm files. I would like to know - what do I need to do to modify the hepler class below (which creates a session factory) so that it uses my ClassMap files instead of hbm?

Also, is this the best way to deal with factory creation? How often will the factory be created in this example - once per request? (I'm not really sure I understand the lifetime of _sessionFactory in this case).

Thank you!

public class NHibernateHelper

{

    private static ISessionFactory _sessionFactory;

    private static ISessionFactory SessionFactory

    {

        get

        {

            if(_sessionFactory == null)

            {

                var configuration = new Configuration();

                configuration.Configure();

                configuration.AddAssembly(typeof(Product).Assembly);

                _sessionFactory = configuration.BuildSessionFactory();

            }

            return _sessionFactory;

        }

    }



    public static ISession OpenSession()

    {

        return SessionFactory.OpenSession();

    }

}
A: 

Session factory usually should only be created once (using the singleton pattern) for the lifetime of the app.

And here is sample code for creating the SessionFactory with Fluent Nhibernate:

var mssqlConfig = MsSqlConfiguration
                .MsSql2008
                .ConnectionString(c => c.Is(connectionstring))
                .UseOuterJoin()
                .ProxyFactoryFactory("NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");

var sessionFactory = Fluently.Configure()
                .Database(mssqlConfig)
                .Mappings(m => m.FluentMappings.AddFromAssembly(typeof(Product).Assembly))
                .BuildSessionFactory();

Not using Fluent Config (from the top of my head, syntax might not be exact):

var config = new NHibernate.Cfg.Configuration().Configure();
var model = new PersistenceModel();
 model.Configure(config);
 model.AddMappingsFromAssembly(typeof(Product).Assembly);

var sessionFactory = config.BuildSessionFactory();
mxmissile
Thanks - If I want to keep the config in the hibernate.cfg.xml, but just use Fluent for the mapping - how would I do that in your code?
UpTheCreek
updated the answer, the syntax might not be exact, don't have my IDE in front of me
mxmissile