如何初始化网络服务的静态变量初始化、变量、静态、网络服务

由网友(╰︶心不凉透难死心)分享简介:我想知道是否有可能以初始化Web服务的C#类的构造函数一些静态变量,所以每次调用Web方法可以使用​​这些变量的内容。举例来说,我想从数据库中加载一些数据,并用它在网上的方法。这样的静态变量将只读。的目的是为了在装入只一次这样的值。或每一个Web方法被调用构造函数时被执行?I would like to know h...

我想知道是否有可能以初始化Web服务的C#类的构造函数一些静态变量,所以每次调用Web方法可以使用​​这些变量的内容。举例来说,我想从数据库中加载一些数据,并用它在网上的方法。这样的静态变量将只读。的目的是为了在装入只一次这样的值。或每一个Web方法被调用构造函数时被执行?

I would like to know how if it is possible to initialize some static variables in the constructor of a web service C# class so each call to a web method can use the content of such variables. For instance, I would like to load some data from the database and use it in the web methods. Such static variable would read-only. The purpose is to have such values loaded only once. Or every time a web method is called the constructor is executed?

推荐答案

是的,每个请求生成Web服务类的新实例。

Yes, every request generates a new instance of your Web Service class.

不过,您可以使用静态构造函数,将初始化一些静态字段。请注意,这些领域将是通用于所有用户和网络服务的所有请求。

However, you can use static constructors, that will initialize some static fields. Note that these fields will be common to all the users and all the requests of your web-service.

public class WebService1 : System.Web.Services.WebService
{

    public static int loadedFromDataBase;

    static WebService1()
    {
        loadedFromDataBase = ...
    }

    [WebMethod]
    public string HelloWorld()
    {
        return loadedFromDataBase.ToString();
    }
}
阅读全文

相关推荐

最新文章