从Web服务实例化对象与从常规类实例化对象

我有一个非常基本的Web服务:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace WebService1 { ///  /// Summary description for Service1 ///  [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class Service1 : System.Web.Services.WebService { public int myInt = 0; [WebMethod] public int increaseCounter() { myInt++; return myInt; } [WebMethod] public string HelloWorld() { return "Hello World"; } } } 

当我运行该项目时,我的浏览器打开显示我的服务: 在此处输入图像描述


在另一个解决方案:(控制台应用程序)

我可以通过添加引用连接到该服务:

在此处输入图像描述

在此处输入图像描述

然后单击添加Web引用按钮: 在此处输入图像描述

最后,我输入我刚刚创建的服务的url: 在此处输入图像描述

现在,我可以从我的控制台应用程序实例化Service1类中的对象,如下所示:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication36 { class Program { static void Main(string[] args) { localhost.Service1 service = new localhost.Service1(); // here is the part I don't understand.. // from a regular class you will expect myInt to increase every time you call // the increseCounter method. Even if I call it twice I always get the same result. int i; i=service.increaseCounter(); i=service.increaseCounter(); Console.WriteLine(service.increaseCounter().ToString()); Console.Read(); } } } 

为什么每次调用increaseCounter方法时myInt都不会增加? 每当我调用该方法时,它返回1。

通过旧的.asmx技术创建的服务不是单例实例。 这意味着您对服务器的每次调用每次都会实例化一个新的服务实例。 两个真正的解决方案,要么使用静态变量(eugh ….),要么切换到使用WCF。

在服务器端,类是通过客户端的每次调用创建和处理的…您的客户端只是一个“代理”,并不直接对应于服务器端的实例…

您可以使myInt static或使服务器端服务类成为Singleton …两个选项都意味着myInt在所有客户端共享…或者您可以实现一些会话管理以实现特定myInt客户端的myInt使用服务器端的WCF似乎是恕我直言的最佳解决方案 – 它带有单例,会话管理等的可配置选项。

编辑 – 根据评论:

使用WCF,您可以使用具有会话管理function的.NET客户端,从而允许您为myInt提供不同的(特定于客户端)值…

webservice实例在每次方法调用结束时被销毁,这就是为什么你总是得到相同的结果。 你需要一些方法来坚持这个价值。