Export (0) Print
Expand All

How to: Control Service Instancing

Setting the instance mode of a service enables you to specify when a System.ServiceModel.InstanceContext (and its associated user-defined service object) is created. See the InstanceContextMode enumeration for the possible modes. For more information about behaviors, see Configuring and Extending the Runtime with Behaviors. For working examples, see Service: Behaviors Samples.

To control the service instance lifetime using code

  1. Apply the ServiceBehaviorAttribute to the service class.

  2. Set the InstanceContextMode property to one of the following values: PerCall, PerSession, or Single.

    [ServiceBehaviorAttribute(InstanceContextMode = InstanceContextMode.PerCall)]
    
    

Example

The following code example sets the InstanceContextMode property of the ServiceBehaviorAttribute attribute to PerCall.

// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
    [OperationContract]
    double Add(double n1, double n2);
    [OperationContract]
    double Subtract(double n1, double n2);
    [OperationContract]
    double Multiply(double n1, double n2);
    [OperationContract]
    double Divide(double n1, double n2);
}

// Service class which implements the service contract.
[ServiceBehaviorAttribute(InstanceContextMode = InstanceContextMode.PerCall)]
public class CalculatorService : ICalculator
{
    public double Add(double n1, double n2)
    {
        return n1 + n2;
    }

    public double Subtract(double n1, double n2)
    {
        return n1 - n2;
    }

    public double Multiply(double n1, double n2)
    {
        return n1 * n2;
    }

    public double Divide(double n1, double n2)
    {
        return n1 / n2;
    }
}

See Also


© 2007 Microsoft Corporation. All rights reserved.
Last Published: 2010-03-21

Community Additions

ADD
Show:
© 2014 Microsoft