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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With