How to create a class that works with TransactionScope?

大憨熊 提交于 2019-12-03 05:36:30

问题


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) { ... }
}

回答1:


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 of IEnlistmentNotification.



来源:https://stackoverflow.com/questions/5265841/how-to-create-a-class-that-works-with-transactionscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!