TransactionScope
TransactionScope is a class in System.Transactions, which is a class that comes with the .NET framework. If the TransactionScope is released without calling the Complete method (TransactionScope implements the IDisposible interface, using block is recommended), then it will consider the operation to fail and will roll back the execution. TransactionScope is a useful API that manages transactions around ("around" means that databases that support TransactionScope can automatically manage transactions), and most mainstream databases support this API, including Microsoft's own MSSQL, of course. If you are using a database or some transaction-related system that does not support TransactionScope, you can still use the interceptor, but you will have to modify your code to use a suitable API that supports transactions (e.g., using the BeginTransaction API to get the database provider's implementation of IDbTransactions).
The above is a custom exception that I deliberately threw to see if it can be rolled back normally, and the picture below is normal execution, without exceptions.
Calling the TransactionScope's Complete method indicates that the transaction is successfully executed. Of course, if the transaction is always executed, then the transaction is not needed. The reason why there are transactions is to solve the problem of failure in multiple operations, and if there is a failure, it will be rolled back. Because the . .NET's TransactionScope, there is no explicit rollback call, and the closest equivalent is to use the Dispose method. If the TransactionScope is released before the Complete method is called, then the TransactionScope performs a rollback. Therefore, a Dispose call needs to be added to the transaction interceptor face to perform the rollback.
Finally, attach the code!
Attached is the source code:Tourists, if you want to see the hidden content of this post, please Reply
|