问题
I m using InstanceContextMode.PerSession in wshttpbinding as mentioned in below code but it seems not working,since my count is not increasing.
Please advice.
[ServiceContract(SessionMode = SessionMode.Required)]
public interface ITransService
{
[OperationContract(IsInitiating=true)]
int Insert(int userId);
[TransactionFlow(TransactionFlowOption.Allowed)]
[OperationContract]
int Update();
// TODO: Add your service operations here
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class TransService : ITransService
{
public int count = 0;
[OperationBehavior(TransactionScopeRequired = true)]
public int Insert(int userId)
{
count = count+1;
return count;
}
[OperationBehavior(TransactionScopeRequired = true)]
public int Update()
{
count = count++;
return count;
}
}
Client Call ---
using (TransactionScope tranScope = new TransactionScope())
{
TransServiceClient obj = new TransServiceClient();
var a= obj.Insert(123);
var b = obj.Insert(123);
var c = obj.Update();
tranScope.Complete();
}
回答1:
In addition to marking the interface as (SessionMode = SessionMode.Allowed)
, you'll also need to define which methods on the interface initiate the session, like so: e.g. if Just Insert initiates the session: [OperationContract(IsInitiating=true)] int Insert(int userId); There's an example here
(No, IsInitiating = true
is the default in any event)
As per the extended commentary, a trial and error approach eventually yielded that TransactionFlow
prevents SessionMode
from working correctly. I cannot currently find a definitive reference on this - the closest to date is this. Logically, sessions can last for far longer durations than Transactions (and given that Transactions could hold locks on database and queue resources) there is some logic.
The solution was to remove TransactionFlow
.
Edit
For those looking to combine both InstanceContextMode = InstanceContextMode.PerSession
and TransactionFlow
, see here
来源:https://stackoverflow.com/questions/27640768/instancecontextmode-persession-not-working