Static class in ASP.NET MVC application

I am wondering if a static class in an ASP.NET MVC application can be initialized more than once . I initially developed my application so that the static component retrieved some things from the database and served as a cache, and I added an update method to the class that was called from the constructor. The update method was also available through the administrative part of the application. At some point, I noticed that the data was updated without using this manual trigger, which means that the static constructor runs more than once.

There are several scenarios where I could reasonably see how this happens, such as an unhandled Exception that causes reinitialization. But I cannot reproduce this, so I would like to know for sure.

+6
source share
2 answers

The most common scenarios would be:

  • web application reload

    • touched web.config
    • touched binaries
    • abnormal termination (memory errors, permission errors)
  • reload application pool

  • restart IIS
  • restart w3wp.exe (at least once every 29 hours!)

The application domain will be rebooted (recompiling the dynamic parts as necessary), and this will invalidate any statically initialized data.

You can work around this by storing static data somewhere if it is expensive to create it, or don’t restart the AppDomain, application pool or IIS server.

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

  • Bye Bye Domain Application
    • he is better at explaining the above. It is noteworthy that IIS will recycle the workflow in just 29 hours, and publicly available hosters will recycle AppDomain more often (possibly after 20 minutes of inactivity).
  • So say ASP.NET: "Hey, I work here!"
    • describes the methods that you can apply to receive notification of a decrease in AppDomain - to use your Singleton instance for correct operation
  • Recommendation

I suggest you read it :)

+10
source

static classes are initialized once for AppDomain.

If IIS recycles your AppDomain, everything will be reinitialized.

+4
source

Source: https://habr.com/ru/post/899410/


All Articles