从Web服务实例化对象与从普通类实例化对象的区别

6

我有一个非常基础的网络服务:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService1
{        
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [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";
        }

    }
}

当我运行该项目时,浏览器会打开并显示服务:enter image description here
在另一个解决方案中(控制台应用程序),我可以通过添加引用连接到该服务: enter image description here enter image description here 然后点击“添加 Web 引用”按钮: enter image description here 最后,我输入刚刚创建的服务的 URL: enter image description here 现在,我可以从我的控制台应用程序中实例化 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。


1
+1 对问题的详细解释。 - Amy B
3个回答

4

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


如果我想让每个客户端根据调用increaseCounter方法的次数显示不同的结果,这在WCF中是可能的吗? - Tono Nam

1

因为在服务器端,每次从客户端发起调用时都会创建和释放该类...你的客户端只是一个“代理”,并不直接对应服务器端的实例...

你可以将myInt设置为static,或者将服务器端服务类设置为Singleton...这两个选项都意味着myInt在所有客户端之间共享...或者你可以实现一些会话管理来实现特定于客户端的myInt... 使用WCF作为服务器端似乎是最好的解决方案 - 它提供了可配置的选项,如单例、会话管理等。

编辑 - 根据评论:

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


0

每次方法调用结束时,webservice实例都会被销毁,这就是为什么你总是得到相同的结果。你需要一些方式来持久化该值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接