我开始使用nHibernate,并希望从第一天开始就这样做,所以这就是我使用ISession的方式。 (根据要求提供网站)
这是我的帮手:
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
}
}
这就是我使用它的方式:
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();
}
}
到目前为止,我得到的就是我应该做的事情,将工作包装在交易中。
我发现,由于ISession对象上的USING语句,会话在每次调用结束时关闭;这就是我添加逻辑以检查Helper.GetCurrentSession调用是否仍然打开的原因。
我这样做了吗?我认为会话是为了保持活着直到请求结束,它确定它何时进入数据库。
我应该简单地提取会话并使用它而不是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();
}
如果是这种情况,我会在其他地方遇到问题吗?
感谢您的时间和帮助。
注意:我确实找到了答案,但我无法将我的问题与任何事情联系起来。如果我错过了,请指点链接。
答案 0 :(得分:0)
我遇到了同样的问题。我现在在请求结束时明确Dispose()
会话 - 解决了问题。
由于我的库也用于非Web应用程序,我的帮助程序类和我的存储库提供了两个入口点 - 一个用于“持久”会话(显式关闭),另一个用于每个行程会话(隐式关闭using
陈述)。
“持久”会话的另一个非常好的用途是,如果您在关系映射上使用延迟加载。如果在检索“父”对象时(通过using
语句)自动关闭会话,然后尝试检索延迟加载属性,则会生成异常,因为会话将会尝试使用已关闭。
<强>更新强>
根据要求,这是我目前的帮助班 - 我的是非常基本的。我的所有配置都在XML文件中。对于我的MVC Web应用程序,我通过调用NHibernateHelper.GetPersistentSession().Dispose()
在EndRequest的监听器中关闭Global.asx中的会话。
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;
}
}