开发者

How to initialize static variables in web services

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. Fo开发者_高级运维r 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?


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜