0

我有一个配置为的 wcf:

ConcurrencyMode = ConcurrencyMode.Multiple,
InstanceContextMode = InstanceContextMode.PerSession

我有一个全局定义的变量,我希望在整个会话期间保持它的值并且它保持那个值。

我有一个实例初始化这个变量并保存它的值(比如 123) 我有另一个实例初始化这个变量并保存它的值(比如 456)

但是,第二个实例初始化变量后,第一个实例(会话)的值变成了456!!没想到!!

我在这里有什么遗漏吗?

4

1 回答 1

1

它应该可以正常工作 - 重新检查您的代码,如下所示。

服务合约:

[ServiceContract]
public interface IService1
{       
    [OperationContract]
    string GetData();      
}

服务实施

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class Service1 : IService1
{
    int i = 0;

    public string GetData()
    {
        i++;
        return string.Format("Instance number: {0}", i);
    }       
}

现在用相同的实例调用服务将从 GetData 给出递增的“int i”值,但对于新实例,它将从 1 开始。

请参阅以下来自客户的电话

using (var client = new HttpProxy.Service1Client("NetTcpBinding_IService1"))
{
    Console.WriteLine("Response {0}", client.GetData());
    Console.WriteLine("Response {0}", client.GetData());
}

using (var client2 = new HttpProxy.Service1Client("NetTcpBinding_IService1"))
{
    Console.WriteLine("Response {0}", client2.GetData());
    Console.WriteLine("Response {0}", client2.GetData());
}

using (var client = new HttpProxy.Service1Client("WSHttpBinding_IService1"))
{
    Console.WriteLine("Response {0}", client.GetData());
    Console.WriteLine("Response {0}", client.GetData());
}

使用 CreateChannel 创建代理实例

var binding = new NetTcpBinding();
                    var address = new EndpointAddress("net.tcp://localhost:8523/Service1");
                    var channelFactory = new ChannelFactory<WcfServLib.IService1>(binding, address);

                    WcfServLib.IService1 proxy = channelFactory.CreateChannel();

                    Console.WriteLine(proxy.GetData());
                    Console.WriteLine(proxy.GetData());


                    channelFactory = new ChannelFactory<WcfServLib.IService1>(binding, address);
                    proxy = channelFactory.CreateChannel();

                    Console.WriteLine(proxy.GetData());
                    Console.WriteLine(proxy.GetData());

                    channelFactory.Close();

服务实施

    [ServiceBehavior(InstanceContextMode= InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)] public class Service1 : IService1 { int i = 0; public string GetData()
    {
        return string.Format("SessionID:{0}, Local variable i:{1}", OperationContext.Current.SessionId, i++);
    }        
}
于 2013-02-01T06:17:04.107 回答