更新时间: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:
TransactionScope
,这将造成严重破坏,因为范围将在NH交易之前完成.TransactionScope
, because the scope will be completed before the NH transaction is.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.