Instancing
Instancing modes in WCF control the way that service objects are allocated to requests.
Once the ServiceHost has been constructed and channel
listeners have been created for each endpoint, requests to each endpoint are processed by
the appropriate service object based on the instancing mode for the service type. Instancing
modes are based on the InstanceContextMode enumeration
from the System.ServiceModel namespace:
PerCallA new service object is created for each call to the service.
PerSessionA new service object is created for each client. This is the default behavior.
SingleA single service object is created and used for all calls from all clients.
You can use the ServiceBehaviorAttribute to set the
InstanceContextMode for each service type. For example,
the following shows how to configure the service type as a singleton:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class SingletonService:ISingletonServiceThis setting essentially controls the lifetime of each service object. The ServiceHost constructs the service instance immediately for
singletons, or when the first request arrives for the service type. Subsequent requests are
directed to the same instance if appropriate, and when the lifetime of the instance has
expired, it is disposed of. In fact, if you implement IDisposable on the service type, you can intercept the Dispose( ) call and potentially clean up allocated resources. Example 5-1 illustrates a service type that shows a message ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access