实例从Web服务对象VS从常规类实例化对象 [英] instantiating an object from a web service vs instantiating an object from a regular class

查看:143
本文介绍了实例从Web服务对象VS从常规类实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very basic web service:

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

    }
}

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

when I run that project my browser opens showing me the service:

我能够连接到该服务通过添加引用:

I am able to connect to that service by adding the reference:

然后单击添加Web引用按钮:

then click on the add web reference button:

最后我型我刚刚创建的服务的URL:

Lastly I type the url of the service I just created:

现在我能够从我的控制台应用程序实例化从类服务对象为:

Now I am able to instantiate an object from the class Service1 from my console application as:

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方法​​的时间?每次我打电话时间的方法将返回1。

why does myInt does not increase every time I call the increaseCounter method? every time I call that method it returns 1.

推荐答案

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

Services created through the older .asmx technology are not singleton instances. This means that each call you make to the server instantiates a new instance of the service each time. Two real solutions, either use static variables (eugh....), or switch to using WCF.

这篇关于实例从Web服务对象VS从常规类实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆