Why is my WebService constructor getting called each time I call a webmethod?

Jeremy Cron picture Jeremy Cron · May 6, 2009 · Viewed 8.8k times · Source

My webservice constructor is getting called each time that I call a webmethod. This is causing some problems with some new functionality that I am adding and I cannot figure out what I am doing wrong to cause this. The only place that I am newing the webservice is in global.asax.cs's Application_Start, but if I remove the code to new the webservice, it still calls the constructor each time that I call a webmethod.

I have tested this by browsing to the .asmx file and calling the webmethod's that way and I have also created a test console application that has a reference to the webservice and will call the methods that way. Both of these give the same results.

I am using c# in ASP.NET 1.1. Any ideas?

Edit:
I am trying to create a heartbeat thread that polls a windows service. I am attempting to save the result in a hash table (multiple threads polling multiple services). I have changed the webmethod (as it used to poll the windows service) to get the results from the hashtable. We are trying to increase the speed of this webmethod call.

Answer

M4N picture M4N · May 6, 2009

Whenever you call a web method, a new instance of the web service is created - this is the intended behaviour. Web services are stateless, which means that an instance of the service is not kept alive between web method calls, and therefore you cannot store any state in members (fields, properties) of the web service.

If you want to save some values/state between web method calls, you have to use the ASP.NET session or a database for that purpose.

See this question for details: Is this supposed to work this way?