How to set the instancing mode in WCF service?

Instancing mode is set in WCF Service on the Service Level using the InstanceContextMode Enum which has these values:

1.       Single--One service instance is allocated for all client calls

2.       PerCall --One service instance is allocated for each client call.

3.       PerSession --One service instance is allocated for each client session

 

Here is an example of how you can set the Instance Mode using the ServiceBehavior Attribute.

 

[ServiceContract]

interface IMyContract {...}

 

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

class MyService : IMyContract {...}

 

 

Here is another example which 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