如何创建一个与 TransactionScope 一起使用的类?
只是想知道,如果我想创建一个执行某些操作的类并且希望能够在 TransactionScope 中使用,我需要实现什么?
也就是说:我的类需要知道它处于事务中,但是如何在提交或回滚时收到通知?关于回滚,我实际上将如何回滚?
我假设我的类将具有“添加”、“更新”和“删除”等方法,这些方法仅修改临时更改列表,以及“读取”方法,该方法需要检测它是否在事务中并返回修改或未修改的数据相应地,但是我需要一个以某种方式被调用的提交/回滚方法?
我会订阅 Transaction.TransactionCompleted 事件吗?如果是,如何避免多次订阅同一交易?
我注意到事务没有 ID,有没有办法管理/处理多个并发事务或嵌套事务?
System.Transactions 的 MSDN 文档有很多内容,但似乎针对消费者而不是实现者,所以我想知道是否有人有关于服务如何为事务提供支持的良好来源(无论是在网络上还是在书中)?
假设我的类没有已经支持事务并且能够“传递它”的底层存储。假设我的课程如下所示:
public class MyClass {
private List<MyObject> _businessData;
public void Create(Myobject data) { ... }
public MyObject Read(string query) { ... }
public void Update(Myobject data) { ... }
public void Delete(Myobject data) { ... }
}
Just wondering, if I want to create a class that does something and I want to be able to be used in a TransactionScope, what would I need to implement?
That is: My class needs to be aware that it's in a Transaction, but how would it get notified on Commit or Rollback? And on Rollback, how would I actually Rollback?
I assume my class would have methods like "Add", "Update" and "Delete" which only modify a temporary list of changes, and a method "Read" which needs to detect if it is in a transaction and return modified or unmodified data accordingly, but then I need a method Commit/Rollback that gets called somehow?
Would I subscribe to the Transaction.TransactionCompleted event? If yes, how do I avoid multiple subscriptions to the same transaction?
I noticed that Transactions do not have IDs, is there a way to manage/juggle with multiple concurrent transactions or nested transactions?
The MSDN Documentation for System.Transactions has a lot of content but it seems to be aimed at consumers rather than implementors, so I wonder if someone has a good source (either on the web or in a book) on how a service would provide support for Transactions?
Let's assume that my Class does not have an underlying store that already supports transactions and is able to just "pass it through". Let's assume my class looks like this:
public class MyClass {
private List<MyObject> _businessData;
public void Create(Myobject data) { ... }
public MyObject Read(string query) { ... }
public void Update(Myobject data) { ... }
public void Delete(Myobject data) { ... }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
本文 对需求有一个很好的概述。它已经很旧了,但我相信这一切仍然适用。
为了总结本文,您需要调用 Transaction 类,传入
IEnlistmentNotification
的实现。This article has a good overview of what is required. It's older, but I believe it all still applies.
To summarize the article, you need to call one of the
Enlist
methods on the Transaction class, passing in an implementation ofIEnlistmentNotification
.