【问题标题】:Transaction on the Client Side客户端交易
【发布时间】:2011-07-30 21:17:30
【问题描述】:

使用 wsdualhttpbinding WCF 的事务使用或理解使用有很大的问题。

我有这样的事情:

IService:

[ServiceContract]
public interface IService
{
  //...
  [OperationContract]
  [ApplyDataContractResolver]
  [TransactionFlow(TransactionFlowOption.Mandatory)] 
  bool SaveDevice(Device device);
  //...
}

Service.svc.cs:

[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
  public class Service : IService
  {
   [OperationBehavior(TransactionScopeRequired = true)]
   public bool SaveDevice(Device device)
   {
            bool temp = false;
            Transaction transaction = Transaction.Current;

            using (EntityConn context = new EntityConn())
            {
                try
                {
                  //....
                }
             }
    }
   }

Model.cs 因此,我在我的客户中尝试执行具有事务要求的操作:

if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
        {
            using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                try
                {
                   //do some stuff
                }
            }
          }

我得到一个错误:Transaction.Current 是空的

  1. 我走对了吗?
  2. 如果没有,我该如何解决?

感谢您的帮助

编辑:我只需要将 if 放在 using 之后

    using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
    {
     if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
     {
            try
            {
               //do some stuff
            }
     }
    }

【问题讨论】:

  • 您的服务正在实现 IService,但您发布的代码有 IVdmService....
  • 谢谢蒂姆!这只是一个错误!
  • 您是否在both 服务和客户端绑定中设置了 transactionFlow 属性(以编程方式或通过配置)?
  • 是的!两个都!交易流=真!

标签: c# wcf transactions


【解决方案1】:

在 TransactionScope 之外,我认为 Transaction.Current 将始终为空。您需要先进入事务范围,然后开始访问 Transaction.Current 的属性。看起来您正试图在客户端执行一些非事务性操作?如果是这样,试试这个:

using (TransactionScope tran = new TransactionScope())
{
    if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
    {
        // ambient transaction is not escalated; exclude this operation from the ambient transaction
        using (TransactionScope tran2 = new TransactionScope(TransactionScopeOption.Suppress))
        {
            // do some stuff
        }
    }
    else
    {
        // ambient transaction is escalated
        // do some other stuff
    }
}

注意:我复制了您在示例代码中的条件,但您应该验证这是正确的测试。 According to MSDNTransactionInformation.DistributedIdentifiernull,而不是 Guid.Empty,在分布式事务之外。

【讨论】:

    【解决方案2】:

    我认为您想在 OperationBehavior 属性上添加 AutoEnlistTransaction=true。同样,您可能需要添加 AutoCompleteTransaction=true。

    【讨论】:

    • OperationBehavior 只有 5 个参数,没有一个不是 AutoEnlistTransaction!我是不是弄错了什么?
    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 2017-03-17
    • 2022-11-02
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多