1

I'm going to hold some static variables inside my RestApi developed in C# ASP.NET MVC (extending ApiControllers).

I want to make sure that this static variables (which act as global variables) in my RestApi method be reinitialized every time a new API method is called. I want to know if web server keep static variables alive or not?

I want to make sure they will not keep alive for next method calls but I'm not sure how does static variables act in RestApis. I read few answers here and here but they seem contradicting and I don't know which one applies to ASP.NET MVC RestAPI too.

VSB
  • 9,825
  • 16
  • 72
  • 145
  • why dont you try it? they are static to the current app pool, so they will stay until you restart it. Save variables in the current context items, if you want them only for one request. – Charles Nov 28 '19 at 10:51
  • 1
    I prefer to understand its behavior based on available documentation. Experimental tries may vary from system to system or version to version. – VSB Nov 28 '19 at 10:55
  • 2
    If you're writing something for asp.net and thinking "static variables" then there's something very wrong here, outside of exceptionally rare situations. We normally expect an asp.net application to be capable of processing *multiple* *independent* requests simultaneously, and they'd all be sharing the same set of static variables. – Damien_The_Unbeliever Nov 28 '19 at 10:58
  • @Damien_The_Unbeliever I need to read some variables from DB during api method call. Inside this method it may happen for many times that I will need this value. So i declared static variable. If it is not `null` it is not read from DB and I access DB to read it. Otherwise I will use static variable current value. Is there any thing wrong about this? (I don't want to use static variables for passing information between consecutive calls of method but I want to use during life cycle of one method call). – VSB Nov 28 '19 at 11:01
  • 1
    Your static vars will live for the life of the app pool, BUT your app pool could restart any time. usually when its idle for too long. So if you want to use static vars, its best to check them for NULL before use, if null, just recreate them. – Charles Nov 28 '19 at 11:10
  • 3
    You can add the value in `HttpContext.Items` and use it in scope of the a API Request. For the next API request, the variable is set again. With the `HttpContext.Items` every API request keeps it's own copy. – user1672994 Nov 28 '19 at 11:42
  • Will this help? https://stackoverflow.com/questions/343899/how-to-cache-data-in-a-mvc-application – Hans Kesting Nov 28 '19 at 12:16
  • 1
    "Experimental tries may vary from system to system or version to version" is an improper attitude. Your experiments should reveal the behaviors and then you try to understand why the behaviors should be expected. Usually that makes your final question posted to sites like this more specific than the one above. – Lex Li Nov 28 '19 at 13:58

0 Answers0