我有一个非常基本的网络服务:
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。
最佳答案
通过旧的 .asmx 技术创建的服务不是单例实例。这意味着每次调用服务器都会实例化一个新的服务实例。两个真正的解决方案,要么使用静态变量(呃....),要么改用 WCF。
关于c# - 从 Web 服务实例化对象与从常规类实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7589301/