Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
Eduardo Mauro Avatar asked Mar 15 '11 11:03

Eduardo Mauro


1 Answers

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();
    }
}
like image 77
SWeko Avatar answered Nov 14 '22 23:11

SWeko