Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

currentsessioncontext fluent nhibernate how to do it?

I am trying to use fluent with session per request. I am following a "recipe" from nhibernate cookbook however it uses the nhibernate config file.

I am not sure what is better but right now I am sticking with fluent config just because I would not know how to set the nhibernate config file to use fluent mapping and vanilla nhibernate mapping(hbm files).

namespace Demo.WebUI
{
    public class MvcApplication : NinjectHttpApplication
    {
        public static ISessionFactory SessionFactory { get; private set; }

        protected override void OnApplicationStarted()
        {
            SessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(
                    c => c.FromConnectionStringWithKey("test")))
                .Mappings(m => m.FluentMappings
                    .AddFromAssemblyOf
                     <Demo.Framework.Data.NhibernateMapping.UserMap>())
                .ExposeConfiguration(BuidSchema)
                .BuildSessionFactory();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var session = SessionFactory.OpenSession();
            //CurrentSessionContext.Bind(session);
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            //var session = CurrentSessionContext.Unbind(SessionFactory);
            SessionFactory.Dispose();
        }
    }
}

As you can see in the Begin_Request the books tutorial had

CurrentSessionContext.Bind(session);

However if I use this it throws a error since I don't have the nhibernate config file in use.

So how do I change it to use fluent configuration? Or do I not even need to do this step?(ie is it done internally?)

like image 498
chobo2 Avatar asked Jan 15 '11 23:01

chobo2


1 Answers

You need to tell NHibernate how to handle the session context. The following might work:

Fluently.Configure()
        ...
        .ExposeConfiguration(cfg => cfg.SetProperty(
                                        Environment.CurrentSessionContextClass,
                                        "web")

Also, unrelated to this: you are disposing the SessionFactory on EndRequest. That is an error.

like image 87
Diego Mijelshon Avatar answered Nov 08 '22 14:11

Diego Mijelshon