它应该可以正常工作 - 重新检查您的代码,如下所示。
服务合约:
[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++);
}
}