currentsessioncontext流利的nhibernate怎么办呢?

cho*_*bo2 8 nhibernate fluent-nhibernate

我正在尝试使用流畅的会话每个请求.我正在遵循nhibernate cookbook的"配方",但是它使用了nhibernate配置文件.

我不确定什么是更好但是现在我坚持使用流畅的配置只是因为我不知道如何设置nhibernate配置文件以使用流畅的映射和vanilla nhibernate映射(hbm文件).

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您在Begin_Request中可以看到的书籍教程

CurrentSessionContext.Bind(session);
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用它,它会抛出一个错误,因为我没有使用nhibernate配置文件.

那么如何更改它以使用流畅的配置?或者我甚至不需要这样做?(即它是在内部完成的吗?)

Die*_*hon 12

您需要告诉NHibernate如何处理会话上下文.以下可能有效:

Fluently.Configure()
        ...
        .ExposeConfiguration(cfg => cfg.SetProperty(
                                        Environment.CurrentSessionContextClass,
                                        "web")
Run Code Online (Sandbox Code Playgroud)

此外,与此无关:您正在EndRequest上处理SessionFactory.那是一个错误.