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:
PerCall
A new service object is created for each call to the service.
PerSession
A new service object is created for each client. This is the default behavior.
Single
A 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:ISingletonService
This 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 ...
Get Learning WCF now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.