C# 我在这里正确使用了nHibernate的会话吗?

C# 我在这里正确使用了nHibernate的会话吗?,c#,asp.net,nhibernate,session,C#,Asp.net,Nhibernate,Session,我从nHibernate开始,希望从第一天开始就做好,所以这里是我如何使用ISession的。每个请求的Web 这是我的助手: using System; using System.Data; using System.Web; using NHibernate; using NHibernate.Cfg; using NHibernate.Cfg.MappingSchema; using NHibernate.Context; using NHibernate.Dialect; using N

我从nHibernate开始,希望从第一天开始就做好,所以这里是我如何使用ISession的。每个请求的Web

这是我的助手:

using System;
using System.Data;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Context;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using NHibernate.Tool.hbm2ddl;

namespace Gigastence.nHibernate.Web
{
    public static class Helper
    {
        #region Public Enums

        public enum DatabaseType
        {
            MSSQL2005,
            MSSQL2008,
            MySQL,
            MySQL5
        }

        #endregion

        #region Private Members

        private static HbmMapping _hbmMapping;
        private static Type[] _mappingTypes;
        private static Configuration _nHibernateConfiguration;

        #endregion

        #region Public Properties

        public static bool GenerateStatistics { get; set; }
        public static string ConnectionString { get; set; }

        public static ISession GetCurrentSession
        {
            get
            {
                //  Store the current ISession
                ISession tempSession = GetSessionFactory.GetCurrentSession();

                //  Return the current Session in for the relevant Context
                return tempSession.IsOpen ? tempSession : OpenSession();
            }
        }

        public static ISessionFactory GetSessionFactory { get; private set; }
        public static DatabaseType WorkingDatabaseType { get; set; }

        #endregion

        #region Private Methods

        private static void CompileSessionFactory()
        {
            //  ToDo: See if we can speed up this process by creating a static file to reference
            //
            //  Build the nHibernate Configuration and store it
            _nHibernateConfiguration = ConfigureNHibernate();

            //  Deserialize and Add the supplied Mappings to the nHibernate Configuration
            _nHibernateConfiguration.AddDeserializedMapping(_hbmMapping, null);

            //  ToDo: Figure out what this does!
            //
            SchemaMetadataUpdater.QuoteTableAndColumns(_nHibernateConfiguration);

            //  Create the Session Factory and store it
            GetSessionFactory = _nHibernateConfiguration.BuildSessionFactory();
        }

        private static Configuration ConfigureNHibernate()
        {
            //  Create a new nHibernate configuration
            var configure = new Configuration();

            //      ToDo: Allow for setting name of SessionFactory
            //
            //  Name the Session Factory
            configure.SessionFactoryName("Default");

            //  Wire up Session Factory Database component based on working database type
            switch (WorkingDatabaseType)
            {
                case DatabaseType.MySQL5:

                    //  !!! Is a MySQL 5 Database
                    configure.DataBaseIntegration(db =>
                    {
                        db.Dialect<MySQL5Dialect>();
                        db.Driver<MySqlDataDriver>();
                        db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                        db.IsolationLevel = IsolationLevel.ReadCommitted;
                        db.ConnectionString = ConnectionString;
                        db.Timeout = 10;
                    });
                    break;
            }

            //  Generate Statistics, if required
            if (GenerateStatistics) configure.SessionFactory().GenerateStatistics();

            //  ToDo: Add modifier based on required Session Context
            //
            configure.CurrentSessionContext<ManagedWebSessionContext>();

            //  Return the Configuration
            return configure;
        }

        #endregion

        #region Public Methods

        public static void AddMapping(Type mappingType)
        {
            //  Determine if array is already available
            if (_mappingTypes == null)
            {
                //  Create a new array with one element
                _mappingTypes = new Type[1];
            }

            //  Copy existing array into a new array with one more element
            Array.Resize(ref _mappingTypes, _mappingTypes.Length + 1);

            //  Add the Mapping Type
            Array.Copy(new object[] { mappingType }, 0, _mappingTypes, _mappingTypes.Length - 1, 1);
        }

        public static void AddMappings(Type[] mappingTypes)
        {
            //  Iterate through passed types
            foreach(Type passedType in mappingTypes)
            {
                //  Add each typre
                AddMapping(passedType);
            }
        }

        public static void Application_BeginRequest()
        {
            //  Add the ISession object to the current request's Context for use throughout the request
            ManagedWebSessionContext.Bind(HttpContext.Current, OpenSession());
        }

        public static void Application_End()
        {
            //  Dispose of the Session Factory
            GetSessionFactory.Dispose();
        }

        public static void Application_EndRequest()
        {
            //  Unbind the Session from the request's context and place in the ISession holder
            ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, GetSessionFactory);

            //  Flush and Close the Session if it is still open
            if (session == null || !session.IsOpen) return;

            //  Proceed
            session.Flush();
            session.Close();
            session.Dispose();
        }

        public static void Application_Error()
        {
            //  Rollback transaction if there is one
            RollbackTransaction();
        }

        public static void BuildDatabase()
        {
            //  ToDo: Tidy Up and extend
            new SchemaExport(_nHibernateConfiguration).Execute(false, true, false);
        }

        public static void BuildSessionFactory(bool forceRebuild)
        {
            //  Determine if this is a forced rebuild
            if (forceRebuild)
            {
                //  !!! Forced rebuild

                //  Compile Session Factory
                CompileSessionFactory();
            }
            else
            {
                //  !!! Not a forced rebuild

                //  Reference the current Session Factory if available
                ISessionFactory sessionFactory = GetSessionFactory;

                //  Determine if Session Factory is built already
                if (sessionFactory == null)
                {
                    //  Compile Session Factory
                    CompileSessionFactory();
                }
            }
        }

        public static void CompileMappings(Type baseEntityToIgnore)
        {
            //  Using the built-in auto-mapper
            var mapper = new ModelMapper();

            //  Add prefetched Types to Mapper
            mapper.AddMappings(_mappingTypes);

            //  Compile the retrieved Types into the required Mapping
            _hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
        }

        public static ISession OpenSession()
        {
            return GetSessionFactory.OpenSession();
        }

        public static void RollbackTransaction()
        {
            //  Get the current ISession from the request's context and place in the ISession holder
            ISession session = GetCurrentSession;

            //  Determine if the ISession exists
            if (session == null) return;

            //  It does, rollback current transaction if there is one
            if (session.Transaction.IsActive && !session.Transaction.WasRolledBack)
            {
                //  There was a transaction, rollback
                session.Transaction.Rollback();
            }
        }

        #endregion
    }
}
到目前为止,我知道这是我应该做的,将工作包装在事务中

但是我发现,由于ISession对象上的USING语句,会话在每次调用结束时都会关闭;这就是为什么我添加了逻辑来检查它在Helper.GetCurrentSession调用中是否仍然处于打开状态

我这样做对吗?我认为会话应该保持活动状态,直到请求结束,并确定何时进入数据库

我应该简单地获取会话并使用它,而不是使用语句:

ISession session = Helper.GetCurrentSession;

using (ITransaction transaction = session.BeginTransaction())
{
    //  Add data to the NHibernateSchemaVersions table
    var table = new NHibernateSchemaVersions { Component = "Web.Provider.Membership", Version = 1 };
    session.Save(table);

    transaction.Commit();
}
如果是这样,我会在其他地方遇到问题吗

谢谢你的时间和帮助


注意:我确实在寻找答案,但我无法将我的问题与任何事情联系起来。如果我错过了一个链接,请给我指一下。

我遇到了同样的问题。我现在在请求问题解决结束时显式地处理会话

由于我的库也用于非web应用程序,我的helper类和我的存储库提供了两个入口点,一个用于显式关闭的持久会话,另一个用于使用using语句隐式关闭的每次行程会话

持久会话的另一个很好的用途是在关系映射上使用延迟加载。如果在通过using语句检索父对象时自动关闭会话,然后尝试检索lazy load属性,则会生成异常,因为它将尝试使用的会话已关闭

更新

根据要求,这是我当前的助手类,我的助手类非常基本。我的所有配置都在一个XML文件中。对于我的MVC web应用程序,我将通过调用NHibernateHelper.GetPersistentSession.Dispose在EndRequest的侦听器中关闭Global.asx中的会话


我想你可能误解了我的问题。虽然我对您拥有的助手更感兴趣,但我的问题与“相同”请求中下次使用之前的会话关闭有关,这是否意味着要发生?提交事务时会话是否关闭?否,提交时会话不会关闭。当您显式关闭或释放会话时,它将关闭。您可以使用一个会话处理多个事务。谢谢Brian。USING语句是否关闭会话?也许这就是我错的地方。是的,是的。using语句基本上将包含的代码包装在try。最后,在finally块中,它调用using语句中指定的项的Dispose方法,在本例中,它是您的会话。基本上,如果您希望在HTTP请求期间打开会话(我假设您的意思是这样),您必须放弃using语句并显式地进行处置,或者找到一种方法将整个请求包装在不推荐的using块中。谢谢,您确认了我的想法。我赢了;t在会话中不再使用using块,除非我必须使用;我的助手的应用程序请求为我处理会话。另一方面,出于厚颜无耻,你认为你能给我提供你的助手的样品吗?我通过例子学习,很简单,有很多例子我不知道哪一个是正确的方法。如果你不这样做也没关系;我不想提供它;完全可以理解。
ISession session = Helper.GetCurrentSession;

using (ITransaction transaction = session.BeginTransaction())
{
    //  Add data to the NHibernateSchemaVersions table
    var table = new NHibernateSchemaVersions { Component = "Web.Provider.Membership", Version = 1 };
    session.Save(table);

    transaction.Commit();
}
public class NHibernateHelper
{
    private static ISessionFactory _sessionFactory;
    private static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)
            {
                var configuration = new NHibernate.Cfg.Configuration();
                configuration.Configure();
                configuration.AddAssembly(typeof(NHibernateHelper).Assembly);
                _sessionFactory = configuration.BuildSessionFactory();
            }
            return _sessionFactory;
        }
    }

    public static ISession OpenSession()
    {
        return SessionFactory.OpenSession();
    }

    private static ISession _persistentSession = null;
    public static ISession GetPersistentSession()
    {
        if (_persistentSession == null)
        {
            _persistentSession = SessionFactory.OpenSession();
        }

        return _persistentSession;
    }
}