Following is the code snippet
Server Code :
namespace WcfService3
{
[ServiceContract]
public interface ICalculator
{
[OperationContract]
string GetCount();
}
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Calculator : ICalculator
{
int count = 0;
public string GetCount()
{
count++;
return "Thread ID : " + Thread.CurrentThread.ManagedThreadId.ToString() + " Counter value : " + count.ToString();
}
}
Client Code
class Program
{
static void Main(string[] args)
{
ICalculator calculator = new ServiceReference2.CalculatorClient();
for (int index = 1; index <= 10; index++)
{
Console.WriteLine(calculator.GetCount());
}
Console.ReadLine();
}
}
If I set InstanceContextMode as InstanceContextMode.Persession or InstanceContextMode.PerCall I get the same result.
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 1
With InstanceContextMode.Single, Counter value increase, This is the expected behavior.
Thread ID : 34 Counter value : 1
Thread ID : 34 Counter value : 2
Thread ID : 34 Counter value : 3
Thread ID : 34 Counter value : 4
Thread ID : 34 Counter value : 5
Thread ID : 34 Counter value : 6
Thread ID : 34 Counter value : 7
Thread ID : 34 Counter value : 8
Thread ID : 34 Counter value : 9
Thread ID : 34 Counter value : 10
I am not able to understand why the value of counter is not increasing with PerCall. Can anybody please explain?
Atul
With PerCall you are taking a new instance of the Calculator service so the count variable is reset. With PerSession you are not, you will be using the same instance until the session expires.
Take a look at this and this