简体   繁体   中英

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. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM