5

I am pretty new in WCF and trying to understand various instance management techniques, I am able to understand Per-Call & Singleton instance mode but i am confused in per session instance mode, In this case for every client a separate session is created right? But its not happening in my case:

My WCF Service:-

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession )]
public class CounterService : ICounterService
{
    int _counter = 0;
    public int GetCount()
    {
        _counter++;
        return _counter;
    }
}

Client Code:-

static void Main(string[] args)
    {
        CounterServiceReference.CounterServiceClient proxy = new     CounterServiceReference.CounterServiceClient();
        CounterServiceReference.CounterServiceClient proxy1 = new CounterServiceReference.CounterServiceClient();
        Console.WriteLine("WCF Instance mode: Per Session");
        Console.WriteLine("Invoking WCF service...");
        Console.WriteLine("Counter: {0}", proxy.GetCount());
        Console.WriteLine("Counter: {0}", proxy.GetCount());
        Console.WriteLine("Counter: {0}", proxy.GetCount());

        Console.WriteLine("---------------------------------------");
        Console.WriteLine("Counter: {0}", proxy1.GetCount());
        Console.WriteLine("Counter: {0}", proxy1.GetCount());
        Console.WriteLine("Counter: {0}", proxy1.GetCount());
        Console.ReadKey();
    }

But, console is displaying result as 1,1,1---1,1,1 but i think it should be 1,2,3---1,2,3 Am i wrong somewhere? Please Help! TIA

4

2 回答 2

5

我认为解释它的最好方法可能是通过这些图表(借自关于该主题的CodePlex 文章):

每个会话的 WCF 每次调用的 WCF 在此处输入图像描述

grock 的主要概念是,当给定的客户端在 PerSession 模式下创建服务的代理时,从该代理对该服务的重复调用将调用相同的服务实例(特定于该客户端)。这允许您在客户端的服务对象中存储一些状态,因为每个客户端都有自己的服务对象实例。

这与 PerCall 和 Singleton 的对比如下:

当您为 PerCall 服务创建代理时,每次调用服务操作时都会获得服务对象的全新实例。

当您为 SingleTon 服务创建代理时,该服务只有一个实例处理所有客户端请求。

于 2013-11-15T21:21:17.737 回答
2

会话意味着您可以使用asp.net中的会话对象,而不是服务对象=它自己被重用。您可以将计数值保存在 Session 对象中,但不会得到预期的结果。结果将是 1,2,3---4,5,6

于 2013-10-29T17:13:28.877 回答