前一篇文章提到希望把事务从业务逻辑里面抽取出来,而且事务控制也是符合面向方面的规则的,通过artech的文章,我们可以很好的理解其中的原理,但是artech的事务辅助类还是需要参杂到业务里面,这里借助aop可以很方便的把事务的控制挪到业务的外围,实际上spring.net里面就是这样做的,spring.net在ado的事务控制方面借助的就是TransactionInterceptor这个方法拦截器,里面的代码大概如下
public object Invoke(IMethodInvocation invocation) { // Work out the target class: may be <code>null</code>. // The TransactionAttributeSource should be passed the target class // as well as the method, which may be from an interface. Type targetType = ( invocation.This != null ) ? invocation.This.GetType() : null; // If the transaction attribute is null, the method is non-transactional. TransactionInfo txnInfo = CreateTransactionIfNecessary( invocation.Method, targetType ); object returnValue = null; try { // This is an around advice. // Invoke the next interceptor in the chain. // This will normally result in a target object being invoked. returnValue = invocation.Proceed(); } catch ( Exception ex ) { // target invocation exception CompleteTransactionAfterThrowing( txnInfo, ex ); throw; } finally { CleanupTransactionInfo( txnInfo ); } CommitTransactionAfterReturning( txnInfo ); return returnValue; }
从代码和注释可以看到,事务的控制在业务方法执行的外围,在业务之前启动事务,如果有异常则回滚事务,正常情况下提交事务。里面的细节部分和artech的原理类似,但是spring.net里面略微复杂点,对于同一个数据库,他里面使用的是同一个连接以及连接上的事务,对于多数据库暂时还没明白,有空深入了解一下;同样对于artech的事务控制,由于自己对于CommittableTransaction不是很了解,虽然大意能明白,但是还是对于事务的细节不是特别了解,有空也得多学习。