How to initialize static variables in web services

I would like to know how some static variables can be initialized in the constructor of the C # class of a web service, so every call to the web method can use the contents of such variables. For example, I would like to download some data from a database and use it in web methods. Such a static variable would be read-only. The goal is to load such values ​​only once. Or every time a web method is called a constructor, is it executed?

+4
source share
1 answer

Yes, each request generates a new instance of your web service class.

However, you can use static constructors that will initialize some static fields. Please note that these fields will be distributed to all users and all 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(); } } 
+8
source

Source: https://habr.com/ru/post/1343760/


All Articles