使用或理解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为空
感谢您的帮助
编辑:我只需要在使用
之后放置if using (var scope = new TransactionScope(TransactionScopeOption.Suppress))
{
if (Transaction.Current.TransactionInformation.DistributedIdentifier == Guid.Empty)
{
try
{
//do some stuff
}
}
}
答案 0 :(得分:1)
在TransactionScope之外,我认为Transaction.Current将始终为null。您需要先输入事务范围,然后开始访问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 MSDN,TransactionInformation.DistributedIdentifier
为null
,而非Guid.Empty
。
答案 1 :(得分:0)
我认为您要在OperationBehavior属性上添加AutoEnlistTransaction = true。同样,您可能希望添加AutoCompleteTransaction = true。