据我从this article了解:
单个:这将帮助我们在全球范围内共享数据。我们可以创造只有一个实例和同一个实例将在后续通话。与“每次会话”相同,这将适用于所有除basicHttpBinding之外的其他绑定。
InstanceContextMode.Single不可用于basicHttpBinding。
但是根据this answer可以。
[This article会增加混乱。
我想获得清晰的答案和解释。
这里是使用basicHttpBinding和InstanceContextMode.Single的示例:
首先是我的Service类,它具有保留请求数的私有字段:
using System.ServiceModel;
namespace WcfService1
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Service1 : IService1
{
private int _singleCounter = 0;//this will be preserved across requests
public Service1()
{
//this constructor executes only ONCE
}
public string GetData()
{
//this will increment with each request
//because it is a SINGLE instance the count
//will be preserved
_singleCounter++;
return string.Format("Requests on this instance: {0}", _singleCounter);
}
}
}
现在我的服务合同:
using System.ServiceModel;
namespace WcfService1
{
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData();
}
}
最后是我的配置文件,使用basicHttpBinding具有单个绑定:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
现在使用Visual Studio附带的默认WCF测试客户端,这里是结果:
[第一个通话计数为1:我不确定为什么有些文章指出basicHttpBinding不支持InstanceContextMode.Single。显然这是不正确的。
我一直将InstanceContextMode.Single与ConcurrencyMode.Multiple结合使用,以始终提供高吞吐量服务。
它还有一个优势,您可以在服务的生命周期中保留一些“状态”,该状态可以在所有请求之间共享。例如,我将常用数据保留在私有字段中,以避免在每次请求时从数据库中加载数据。