2012-01-12 68 views
0

,共享事務我想不同的調用共享相同的事務。最初的想法是保持一個靜態指向活動事務,但這不是線程保存,並且由於我正在編寫一個WCF服務,我應該考慮這樣的事情。我不想「靜態」,而是想要對當前上下文靜態的東西。技巧與多線程

// The main idea 
public override void SaveItem() 
{ 
    using (var transaction = BeginSharedTransaction()) 
    { 
     other1.Save(); 
     base.SaveItem(); 
     other2.Save(); 
     transaction.Commit(); 
    } 
} 

// In the base class 
public void Save() { ... SaveItem(); ... } 
protected virtual void SaveItem() { ... } 

// In the base class (or another helper class) 
static SqlTransaction _sqlTran = null; 
public static SqlTransaction BeginSharedTransaction() 
{ 
    _sqlTran = ... // conn.BeginTransaction(); 
    return _sqlTran; 
} 

如果可能,我寧願選擇不涉及TransactionScope的解決方案。

編輯 - 我想我們都同意在服務中static SqlTransaction是壞的,但這是非線程環境的最初想法。

+0

是否有一個地方共享交易實際上是有用的,你可以跟我們分享的情景? – 2012-01-12 10:29:57

+0

在我的示例中,事務在調用者「other1」和「other2」之間共享。 – 2012-01-12 10:33:28

+1

你提到WCF,而且作爲InstanceContextMode你使用不提供任何指示,或者是否/如何你使用WCF的TransasctionScopeOption屬性。 WCF應該能夠爲你做很多這種管道工作。 – 2012-01-12 12:51:58

回答

1

如果「共享」你的意思是使用在基類和派生類完成的SQL操作相同的交易對象,你可以只移動事務在基類處理邏輯,並給獲得的機會加上它自己的實現,就像這樣:

// In the base class 
protected SqlTransaction Transaction; 

public void Save() 
{ 
    ... 
    using (var transaction = BeginSharedTransaction()) 
    { 
     Save(Transaction); 

     transaction.Commit(); 
    } 
    ... 
} 

public void Save(SqlTransaction transaction) 
{ 
    Transaction = transaction; 
    SaveItem(); 
} 

protected virtual void SaveItem() { ... /* uses Transaction on all SQL commands */ ... } 

// in the derived class 
public override void SaveItem() 
{ 
    other1.Save(Transaction); 
    base.SaveItem(); 
    other2.Save(Transaction); 
} 


// In the base class (or another helper class) 
public static SqlTransaction BeginSharedTransaction() 
{ 
    return ... // conn.BeginTransaction(); 
} 

(代碼根據註釋更新)

+0

但是,其他1.Save()和other2.Save()將嘗試開始並提交事務。 – 2012-01-12 10:31:40

+0

你是對的;我錯過了。我會找到一個解決方案並更新代碼 – GolfWolf 2012-01-12 10:36:51

+0

我已經更新了代碼 - 我建議使用'void Save(SqlTransaction事務)'重載,允許將現有事務注入給定的'ClassWithUnknownNameThatDoesSomeSqlStuff'實例 – GolfWolf 2012-01-12 10:45:57