NHibernate.HibernateeException:没有绑定到当前上下文的会话

NHibernate.HibernateeException:没有绑定到当前上下文的会话,nhibernate,fluent-nhibernate,ninject,Nhibernate,Fluent Nhibernate,Ninject,我正在一个新项目中工作,我正在尝试在asp.net mvc中用ninject实现nhibernate。我有一个错误: NHibernate.HibernateeException:没有绑定到当前上下文的会话 下面是我正在使用的代码: using FluentNHibernate.Automapping; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using FluentNHibernate.Conventions.Hel

我正在一个新项目中工作,我正在尝试在asp.net mvc中用ninject实现nhibernate。我有一个错误:

NHibernate.HibernateeException:没有绑定到当前上下文的会话

下面是我正在使用的代码:

using FluentNHibernate.Automapping;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions.Helpers;
using NHibernate;
using NHibernate.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestNhibernateSessions
{
    public class SessionFactory : IHttpModule
    {
        private static readonly ISessionFactory _SessionFactory;
        static SessionFactory()
        {
            _SessionFactory = CreateSessionFactory();
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += BeginRequest;
            context.EndRequest += EndRequest;
        }
        public void Dispose()
        {
        }
        public static ISession GetCurrentSession()
        {
            return _SessionFactory.GetCurrentSession();
        }

        private static void BeginRequest(object sender, EventArgs e)
        {
            ISession session = _SessionFactory.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);
        }

        private static void EndRequest(object sender, EventArgs e)
        {
            ISession session = CurrentSessionContext.Unbind(_SessionFactory);
            if (session == null) return;
            try
            {
                session.Transaction.Commit();
            }
            catch (Exception)
            {
                session.Transaction.Rollback();
            }
            finally
            {
                session.Close();
                session.Dispose();
            }
        }

        private static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                           .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))
                           .Mappings(m => m.AutoMappings.Add(CreateMappings()))
                           .CurrentSessionContext<WebSessionContext>()
                           .BuildSessionFactory();
        }

        private static AutoPersistenceModel CreateMappings()
        {
            return AutoMap
                .Assembly(System.Reflection.Assembly.GetCallingAssembly())
                .Where(t => t.Namespace != null && t.Namespace.EndsWith("Domain"))
                .Conventions.Setup(c => c.Add(DefaultCascade.SaveUpdate()));
        }
    }
}

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(TestNhibernateSessions.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(TestNhibernateSessions.App_Start.NinjectWebCommon), "Stop")]

namespace TestNhibernateSessions.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using TestNhibernateSessions.Repository;
    using TestNhibernateSessions.Service;
    using NHibernate;


    public static class NinjectWebCommon
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {



            kernel.Bind<IProductRepository>().To<ProductRepository>();
            kernel.Bind<IProductService>().To<ProductService>();


        }
    }
}
使用FluentNHibernate.Automapping;
使用FluentNHibernate.Cfg;
使用FluentNHibernate.Cfg.Db;
使用FluentNHibernate.Conventions.Helpers;
使用NHibernate;
使用NHibernate.Context;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用System.Web;
命名空间TestNhibernateSessions
{
公共类SessionFactory:IHttpModule
{
私有静态只读ISessionFactory _SessionFactory;
静态SessionFactory()
{
_SessionFactory=CreateSessionFactory();
}
公共void Init(HttpApplication上下文)
{
context.BeginRequest+=BeginRequest;
context.EndRequest+=EndRequest;
}
公共空间处置()
{
}
公共静态ISession GetCurrentSession()
{
返回_SessionFactory.GetCurrentSession();
}
私有静态void BeginRequest(对象发送方,事件参数e)
{
ISession session=_SessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(会话);
}
私有静态void EndRequest(对象发送方,事件参数e)
{
ISession session=CurrentSessionContext.Unbind(_SessionFactory);
if(session==null)返回;
尝试
{
Commit();
}
捕获(例外)
{
session.Transaction.Rollback();
}
最后
{
session.Close();
session.Dispose();
}
}
私有静态ISessionFactory CreateSessionFactory()
{
流畅地返回。Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c=>c.fromConnectionString WithKey(“默认连接”))
.Mappings(m=>m.AutoMappings.Add(CreateMappings()))
.CurrentSessionContext()
.BuildSessionFactory();
}
私有静态AutoPersistenceModel CreateMappings()
{
返回自动映射
.Assembly(System.Reflection.Assembly.GetCallingAssembly())
.Where(t=>t.Namespace!=null&&t.Namespace.EndsWith(“域”))
.Conventions.Setup(c=>c.Add(DefaultCascade.SaveUpdate());
}
}
}
[assembly:WebActivatorEx.PreApplicationStartMethod(typeof(TestNhibernateSessions.App_Start.NinjectWebCommon),“Start”)]
[assembly:WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(TestNhibernateSessions.App_Start.NinjectWebCommon),“停止”)]
命名空间TestNhibernateSessions.App\u开始
{
使用制度;
使用System.Web;
使用Microsoft.Web.Infrastructure.DynamicModuleHelper;
使用Ninject;
使用Ninject.Web.Common;
使用TestNhibernateSessions.Repository;
使用TestNhibernateSessions.Service;
使用NHibernate;
公共静态类NinjectWebCommon
{
私有静态只读引导程序Bootstrapper=new Bootstrapper();
/// 
///启动应用程序
/// 
公共静态void Start()
{
RegisterModule(typeof(OnePerRequestHttpModule));
RegisterModule(typeof(NinjectHttpModule));
初始化(CreateKernel);
}
/// 
///停止应用程序。
/// 
公共静态无效停止()
{
bootstrapper.ShutDown();
}
/// 
///创建将管理应用程序的内核。
/// 
///创建的内核。
私有静态IKernel CreateKernel()
{
var kernel=新的标准内核();
尝试
{
kernel.Bind().ToMethod(ctx=>()=>newbootstrapper().kernel);
kernel.Bind().To();
注册服务(内核);
返回内核;
}
抓住
{
Dispose();
投掷;
}
}
/// 
///在这里加载您的模块或注册您的服务!
/// 
///内核。
私有静态无效注册服务(IKernel内核)
{
kernel.Bind().To();
kernel.Bind().To();
}
}
}

既然您使用的是Ninject,我的建议是使用它来注入会话工厂,而不是IHTTP模块。为此,创建Ninject提供程序类,如下所示。请注意,这需要在代码中进行事务管理,我不喜欢在请求期间盲目地保留打开的事务

public class SessionFactoryProvider : Provider<ISessionFactory>
{
    protected override ISessionFactory CreateInstance(IContext context)
    {
        return Fluently.Configure()
                       .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))
                       .Mappings(m => m.AutoMappings.Add(CreateMappings()))
                       .CurrentSessionContext<WebSessionContext>()
                       .BuildSessionFactory();
    }
}

public class SessionProvider : Provider<ISession>
{
    protected override ISession CreateInstance(IContext context)
    {
        var sessionFactory = context.Kernel.Get<ISessionFactory>();
        var session = sessionFactory.OpenSession();
        session.FlushMode = FlushMode.Commit;
        return session;
    }
}
公共类SessionFactoryProvider:提供程序
{
受保护的重写ISessionFactory CreateInstance(IContext上下文)
{
流畅地返回。Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(c=>c.fromConnectionString WithKey(“默认连接”))
.Mappings(m=>m.AutoMappings.Add(CreateMappings()))
.CurrentSessionContext()
.BuildSessionFactory();
}
}
公共类SessionProvider:提供程序
{
受保护的覆盖ISession CreateInstance(IContext上下文)
{
var sessionFactory=context.Kernel.Get();
var session=sessionFactory.OpenSession();
session.FlushMode=FlushMode.Commit;
返回会议;
}
}
然后在NinjectWebCommon中:

private static void RegisterServices(IKernel kernel)
{
    // session factory instances are singletons
    kernel.Bind<ISessionFactory>().ToProvider<SessionFactoryProvider>().InSingletonScope();
    // session-per-request
    kernel.Bind<ISession>().ToProvider<SessionProvider>().InRequestScope();
}
私有静态无效注册服务(IKernel内核)
{
//会话工厂实例是单例的
内核.Bin