我让 Ninject 管理我的ISession
and ITransaction
使用以下注册方法在 Fluent nHibnerate 中进行状态 - 我想知道它是否足以控制事务,或者我是否需要将其放在其他地方。
想法是,每个ISession
根据请求创建,Ninject 处理该请求期间完成的所有操作的提交。
public class SessionModule : Ninject.Modules.NinjectModule
{
private static ISessionFactory sessionFactory;
public override void Load()
{
Bind<ISessionFactory>()
.ToMethod(c => CreateSessionFactory())
.InSingletonScope();
Bind<ISession>()
.ToMethod(c => OpenSession())
.InRequestScope()
.OnActivation(session =>
{
session.BeginTransaction();
session.FlushMode = FlushMode.Commit;
})
.OnDeactivation(session =>
{
if (session.Transaction.IsActive)
{
try
{
session.Flush();
session.Transaction.Commit();
}
catch
{
session.Transaction.Rollback();
}
}
});
}
/// <summary>
/// Create a new <see cref="NHibernate.ISessionFactory"/> to connect to a database.
/// </summary>
/// <returns>
/// A constructed and mapped <see cref="NHibernate.ISessionFactory"/>.
/// </returns>
private static ISessionFactory CreateSessionFactory()
{
if (sessionFactory == null)
sessionFactory = Persistence.SessionFactory.Map
(System.Web.Configuration
.WebConfigurationManager
.ConnectionStrings["Local"]
.ConnectionString
);
return sessionFactory;
}
/// <summary>
/// Open a new <see cref="NHibernate.ISession"/> from a <see cref="NHibernate.ISessionFactory"/>.
/// </summary>
/// <returns>
/// A new <see cref="NHibernate.ISession"/>.
/// </returns>
private static ISession OpenSession()
{
// check to see if we even have a session factory to get a session from
if (sessionFactory == null)
CreateSessionFactory();
// open a new session from the factory if there is no current one
return sessionFactory.OpenSession();
}
}
我已经使用检查了运行时System.Diagnostics.Debug.WriteLine
当事情发生时写下来does看起来这是我做的wanted它要做。我想问你们,社区,这是否是一个good练习与否。这是我的理解。
无数个小时的阅读http://ayende.com/blog/default.aspx http://ayende.com/blog/default.aspx让我重新评估了很多会话管理的方式。
对 nHibernate 文档的深入研究告诉我我需要使用ITransaction
每次我的数据库发生任何事情时.
将管理放在属性中被认为是一个缺陷,因为它不遵守上述声明。
Doing ITransaction
每个单独的操作不是正确的过程,因为它需要 (A) 我的控制器能够访问ISession
或 (B) 我的IRepository<T>
拥有ITransaction
逻辑,我在之前的问题中已经被告知这不是一个好的做法。
放置我的ITransaction
管理在HttpModule
增加了不必要的开销,因为它让我的 HttpContext 了解ISession
这意味着我必须进行某种注入HttpRequest
(我可以使用[Inject]
,但这似乎并不明智)
这让我得出了这个结论。
- 交易应在以下情况下开始:
ISession
被要求。
- 发生在一个单一请求被封装为one
ISession
- When an
ITransaction
完成后,需要提交,以便二级缓存可以获得其结果。
谁能阐明这一点?我终于走上正轨了吗?还是我完全没有抓住要点?