【问题标题】:instantiating an object from a web service vs instantiating an object from a regular class从 Web 服务实例化对象与从常规类实例化对象
【发布时间】:2011-09-28 20:37:49
【问题描述】:

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

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";
        }

    }
}

当我运行该项目时,我的浏览器会打开,向我显示服务:


在不同的解决方案上:(控制台应用程序)

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

然后点击添加网页参考按钮:

最后我输入刚刚创建的服务的 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。

【问题讨论】:

  • +1 以获得对问题的彻底解释。

标签: c# asp.net webrequest


【解决方案1】:

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

【讨论】:

  • 所以如果我希望每个客户端显示不同的结果,具体取决于他调用 WCF 可能实现的 increaseCounter 方法的次数?
【解决方案2】:

因为在服务器端,类是由您从客户端发出的每个调用创建和处理的...您的客户端只是一个“代理”,并不直接对应于服务器端的实例...

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

编辑 - 根据 cmets:

使用 WCF,您可以拥有带有会话管理的 .NET 客户端,这反过来又允许您为 myInt 设置不同的(特定于客户端的)值...

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      相关资源
      最近更新 更多