2012-01-12 71 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