Detecting a Dispose() from an exception inside using block

前端 未结 8 510
暖寄归人
暖寄归人 2021-02-01 19:13

I have the following code in my application:

using (var database = new Database()) {
    var poll = // Some database query code.

    foreach (Question question          


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 19:35

    Look at the design for TransactionScope in System.Transactions. Their method requires you to call Complete() on the transaction scope to commit the transaction. I would consider designing your Database class to follow the same pattern:

    using (var db = new Database()) 
    {
       ... // Do some work
       db.Commit();
    }
    

    You might want to introduce the concept of transactions outside of your Database object though. What happens if consumers want to use your class and do not want to use transactions and have everything auto commit?

提交回复
热议问题