Instance mode is basically a service side implementation detail. It should not manifest itself on the client side. WCF defines the behaviors. Behavior is a local attribute of a service or client that does not affect communication. The client never knows about the service behavior and does not manifest service binding or published metadata.
Instance Modes available in WCF are:
- PerCall
- PerSession
- Single
PerCall Services
When a service is configured PerCall, every client gets a new service instance. The above diagram shows how a PerCall instance works:
- Client calls the proxy and proxy forwards the call to service.
- WCF creates an instance and calls the method call.
- When method call returns, WCF calls IDisponsible if implemented.
PerSession Service
WCF maintains a logical session between client and service in Persession instance mode. A new instance of the service class is created for each client.
The following given diagram represents the request from the client using Persession service instance mode:
Single Instance Service
When we configure a service as a singleton, all clients are connected to a single instance context. We configure a singleton service by setting the InstanceContextMode property as single. Only one instance is created upon creation of a service host. This instance is forever for the service. Another service instance is created only when we reset the IIS or when the service host is shut down.
Diagrammatic representation of a singletion instance:
When should you use per call, per session, and single mode?
Per call:
- You want a stateless service.
- Your service holds intensive resources like connection objects and huge memory objects.
- Scalability is a prime requirement. You would like to have a scaled out architecture.
- Your WCF functions are called in a single threaded model.
Per session:
- You want to maintain states between WCF calls.
- You a scaled up architecture.
- Light resource references.
Single:
- You want share global data through your WCF service.
- Scalability is not a concern.