Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static class in Asp.NET MVC app

Tags:

c#

asp.net-mvc

I am wondering if a static class in an ASP.NET MVC app could be initialized more than once. I initially designed my app so that a static component would fetch some stuff from the database and serve as a cache, and I added a refresh method to the class which was called from the constructor. The refresh method was also made available through the administration portion of the app. At some point I noticed that the data was updated without requiring this manual trigger, which implies that the static constructor run more than once.

There are several scenarios where I could reasonably see this happen, such as an unhandled Exception causing re-initialization. But I am having trouble reproducing this, so I would like to know for sure.

like image 782
Gleno Avatar asked Oct 16 '11 19:10

Gleno


2 Answers

The most usual scenarios would be:

  • a reload of the web application

    • touched Web.config
    • touched binaries
    • abnormal termination (out-of-memory, permission errors)
  • a reload of the Application Pool

  • a restart of IIS
  • a restart of w3wp.exe (at least once in 29 hours!)

The app-domain will get reloaded (recompiling the dynamic parts as necessary) and this would void any statically initialized data.

You can get around that by persisting the static data somewhere if creating it is expensive, or avoid reloading the AppDomain, the Application Pool or the IIS server.

Update: Phil Haack just published a relevant blog entry here: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx

  • Bye Bye App Domain
    • it does a better job at explaining the above. Notable, IIS will recycle it's worker process very 29 hours at minimum and shared hosters will recycle AppDomain much more often (perhaps in 20 minutes of idle time)
  • So tell ASP.NET, “Hey, I’m working here!”
    • outlines techniques you can apply to get notified of an AppDomain take down - you could use this to get your Singleton instance behaving 'correctly'
  • Recommendation

I suggest you read it :)

like image 156
sehe Avatar answered Nov 11 '22 21:11

sehe


static classes are initialized once per AppDomain.

If IIS recycles your AppDomain, everything will re-initialize.

like image 42
SLaks Avatar answered Nov 11 '22 20:11

SLaks