currentsessioncontext fluent nhibernate how to do it?

人走茶凉 提交于 2019-12-09 16:01:20

问题


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?)


回答1:


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.




回答2:


If your project is Asp.Net web site (not web application ), in Global.asax you should use like that

NHibernate.Cfg.Environment.CurrentSessionContextClass



来源:https://stackoverflow.com/questions/4702703/currentsessioncontext-fluent-nhibernate-how-to-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!