且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在事务中包装延迟加载?

更新时间:2023-10-30 22:07:46

实际上,这仍然是一个隐式事务,或者相对接近.注入器非常高兴地不知道激活和停用之间发生的一切,并且即使状态不正确或已损坏,也会高兴地尝试提交所有更改.

This is, in fact, still an implicit transaction, or relatively close to it. The injector is blissfully ignorant of everything that's happened between activation and deactivation and will happily try to commit all your changes even if the state is incorrect or corrupted.

我看到的是,您实质上是在作弊,只是让Ninject在每个请求的开头自动启动一个事务,并在每个请求的结尾提交该事务,希望它可以阻止NH抱怨.出于以下几个原因,这是极端的不良设计:

What I see is that you're essentially trying to cheat and just have Ninject automatically start a transaction at the beginning of every request, and commit the transaction at the end of every request, hoping that it will stop NH from complaining. This is extremely bad design for several reasons:

  1. 即使会话完全没有使用(即打开虚假连接),您也正在强制进行交易.
  2. 没有异常处理-如果操作失败或被回滚,清理代码将忽略该异常并尝试进行提交.
  3. 如果您尝试使用TransactionScope,这将造成严重破坏,因为范围将在NH交易之前完成.
  4. 您无法完全控制交易真正发生的时间,而放弃了(例如)在单​​个请求中进行多个交易的能力.
  1. You are forcing a transaction even if the session is not used at all (i.e. opening spurious connections).
  2. There is no exception handling - if an operation fails or is rolled back, the cleanup code simply ignores that and tries to commit anyway.
  3. This will wreak havoc if you ever try to use a TransactionScope, because the scope will be completed before the NH transaction is.
  4. You lose all control over when the transactions actually happen, and give up your ability to (for example) have multiple transactions within a single request.

NH Profiler完全正确.这不适用于NH交易.实际上,如果您是懒加载,那么在您仍在迭代结果的同时交易可能最终会被提交-情况不妙.

The NH Profiler is exactly right. This isn't appropriate use of NH transactions. In fact, if you're lazy loading, the transaction might end up being committed while you're still iterating the results - not a good situation to be in.

如果您希望对事务逻辑进行有用的抽象,并且不想与ISession对象发生纠缠,请使用

If you want a useful abstraction over the transactional logic and don't want to have to twiddle with ISession objects then use the Unit Of Work pattern - that's what it's designed for.

否则,请正确编码您的交易,并在实际代表交易的操作周围使用using子句.是的,这是额外的工作,但是您不能轻易地欺骗它.

Otherwise, please code your transactions correctly, with a using clause around the operations that actually represent transactions. Yes, it's extra work, but you can't cheat your way out of it so easily.