根据性能的要求,WCF提供了3种Service Instance的管理方式
1.Per-Call Service:客户端每次调用Function时,生成一个新的实例(意味着构造函数每次都回调用),当结束调用时,自动释放这个实例(调用Dispose,释放资源)。
服务端设置:[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall )]
public class Service {}
特点:节省资源。
2.Per-Session Service:默认的Service Instance(主要指的是Transport-Level Session)。一个Client Proxy对应一个Private Session。
服务端设置:[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession )]
除了服务端设置之外,客户端也需要知道能否使用Session,通过SessionMode属性来设置,包括3种:
(1)SessionMode.Allowed(默认值)
[ServiceContract(SessionMode = SessionMode.Allowed)]
interface IMyContract{}
只有:如果服务使用的WSHttpBinding绑定包含了安全(为默认配置)或者可靠的消息传输,或者使用NetTcpBinding绑定、NetNamedPipeBinding绑定,服务才为Session Serivce;
(2)SessionMode.Required。
当服务为Session时,建议设置为此项。(在服务装载期间,进行安全的验证和Transport-Level Session)
(3)SessionMode.NotAllowed,将服务设置为Per-Call。
(4)避免将不同的SessionMode,比如SessionMode.Required和SessionModeNotAllowed,应用到同一个Service(一个Service应该提供统一的InstanceMode)。
[ServiceContract(SessionMode = SessionMode.Required )]
interface IMyContract
{...}
[ServiceContract(SessionMode = SessionMode.NotAllowed )]
interface IMyOtherContract
{...}
//Avoid
class MyService : IMyContract,IMyOtherContract
{...}
(5) 针对Session Sercice,(客户端和服务端)设置可靠的传输和空闲超时值(默认为10分钟)
<reliableSession enabled = "true" inactivityTimeout = "00:25:00"/>
3.Singleton Service:只有一个实例,永远不会过期,除非关闭ServiceHost。
服务端设置:[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single )]
public class Service {}
只要是Singleton Service,即使Service支持不同的IContract(比如SessionMode.Allowed和SessionMode.Required),也是按照一个Instance来调用的(Singleton优先级最高)。
由于SingletonService的同步性很难,所以为了得到更好的scalability,应该尽可能避免它。
4。针对Session Service ,意味着Demarcating Operations,为不同的Method提供一个指定的顺序,两个属性的设置。
(1)IsInitiating,默认值为True。(如果设置为False,表示该Method不能第一个被调用)
(2)IsTerminate,默认值为False。(如果设置为True,表示该Method如果被调用之后,该Session Service将被释放资源)
[OperationContract(IsInitiating = false)]
void AddItem(int itemId);
5.针对Session Service ,可以定义Instance Deactivation,允许Context和Instance有着不同的Life Cycle。包括四种ReleaseInstanceMode:None, BeforeCall, AfterCall, BeforeAndAfterCall。
在不同的Method上,实施ReleaseInstanceMode,避免在一个Service整体应用。
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service1 : IService1,IDisposable
[OperationBehavior(ReleaseInstanceMode = ReleaseInstanceMode.BeforeCall)]
public void MyMethod() {}
BeforeCall:在调用该Method之前,如果已经有一个Instance在运行,WCF将Deactivate(释放资源),然后创建新的Instance,调用该Method.类似于“Open”操作。
AfterCall:在调用该Method之后,WCF将Deactivate(释放资源).类似于"Close"操作。
6.Throttling(限流)
限流“允许开发者限制客户端连接数以及服务的负荷。限流可以避免服务的最大化,以及分配与使用重要资源的最大化。引入限流技术后,一旦超出配置的设置 值,WCF就会自动地将等待处理的调用者放入到队列中,然后依次从队列中取出。在队列中等待处理调用时,如果客户端的调用超时,客户端就会获得一个 TimeoutException异常。每个服务类型都可以应用限流技术,也就是说,它会影响到服务的所有实例以及服务类型的所有终结点。实现方式是为限 流与服务使用的每个通道分发器建立关联。”
<serviceBehaviors>
<behavior name = "ThrottledBehavior">
<serviceThrottling
maxConcurrentCalls = "16"
maxConcurrentSessions = "10"
maxConcurrentInstances = "Int.MaxValue"
/>
</behavior>
</serviceBehaviors>