title: Static variables in .net web api server
body: <p>I have a web api server which basically responds to 2 requests: stop and start.</p>
  
  <p>On start it does several things, for example, initializing timers that perform a method every X seconds, and on stop it just stops the timers.</p>
  
  <p>In order to achieve that, I created a singleton class which handles the logic of the operations. (It needs to be singleton so the timers and more variables will exist only once for all the requests).</p>
  
  <p>Server is running fine, but recently I got a AccessViolationException while accessing Globalconfiguration.AppSettings in order to retrieve a value from my webconfig file.</p>
  
  <p>I found out by looking at my logs that the singleton class finalizer was called, even though I didn't restart the server.</p>
  
  <p>The finalizer calls a method which I regularly use and works fine in other scenarios, and this method uses the GlobalConfiguration class which threw the exception.</p>
  
  <p>I tried to find the cause for this without success.</p>
  
  <p>So basically there are two bugs here:
  1. Why was the finalizer called out of the blue? The server could run for a week.
  2. The AccessViolationException. </p>
  
  <p>Perhaps the bugs are related? If my application memory was somehow cleaned would it cause the finalizer to be called and an exception accessing the GlobalConfiguration? Just a theory....</p>
  
  <p>Or perhaps maybe I don't handle the singleton properly? But, after reading about static variables in c# web servers I see that they should exist while the application exist, and as such the bug might not be related with handling the singleton. I do handle it OK - the singleton has a private static field which holds the actual instance and the initialization occurs via locking and double checking to prevent multiple threads creating the singleton.</p>
  
  <p>Is my approach OK? Do you see any possible bug that I didnt expect in this behavior, or do you know of any behavior of the .net framework that could cause my static singleton to be destroyed?</p>