WCF InstanceContextMode.PerSession [英] WCF InstanceContextMode.PerSession
问题描述
如果我使用这个:InstanceContextMode.PerSession,那么对于每个客户端,我都会初始化我的服务一次.我说得对吗?
if I use this: InstanceContextMode.PerSession, then for every client I initialize my service one time. Am I right?
如果我调用具有 [OperationBehavior(TransactionScopeRequired = true)] 的方法,则会调用 JobImplement 构造函数.为什么?
我的服务:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class JobImplement : IJob
{
public static int Sum = 0;
public JobImplement()
{
Sum++;
}
[OperationBehavior(TransactionScopeRequired = true)]
public void UselessMethod1()
{
}
[OperationBehavior(TransactionScopeRequired = true)]
public void AddEmployee(string Name, string Age)
{
}
public int GetSum()
{
return Sum;
}
}
编辑 1:
我使用 WSHttpBinding 绑定,这是我唯一的客户端代码.
Im using WSHttpBinding binding and here is my only client code.
我的客户:
static void Main(string[] args)
{
ServiceReference1.IJob Service1 = new ServiceReference1.JobClient();
Service1.UselessMethod1();//sum become [1]
Service1.AddEmployee("","");//sum become [2]
Console.WriteLine(Service1.GetSum());//show [2].
Console.WriteLine(Service1.GetSum());//show [2].
Console.WriteLine(Service1.GetSum());//show [2].
}
推荐答案
此处编写的服务使用 ServiceBehavior.ReleaseServiceInstanceOnTransactionComplete
属性的默认值,即 true
.
The service as written here uses the default value of the ServiceBehavior.ReleaseServiceInstanceOnTransactionComplete
attribute, which is true
.
这意味着通过 TransactionScopeRequired
强制执行事务范围的方法将导致服务实例被释放,并且下次调用方法时,尽管您需要InstanceContextMode代码>.
This means that the methods enforcing transaction scope via TransactionScopeRequired
will cause the service instance to be released and the next time a method is invoked, a new instance gets created despite your desired InstanceContextMode
.
将相关属性更改为 false
应该可以解决问题.
Changing the relevant attribute to false
should solve the problem.
这篇关于WCF InstanceContextMode.PerSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!