Question

I have tried both static C# constructors (for MVC controllers) and Global.asax.cs but unfortunately the application seems to linger, so when one user exits, and another opens the MVC application, the static variable initialization does not (always) take place. Apparently, these static variables "live" beyond an application instance (i.e. when the app opens and closes on a website).

Does anyone know methods that will always work at the opening and/or closing of the MVC web site (i.e. the main index page)? I need to re-initialize my static C# controller members at this time....

Thanks in advance.

Was it helpful?

Solution

The life cycle of a website has got very little to do with individual users. Indeed, in recent versions of IIS it doesn't even need an incoming request to start the app - it can elect to do that pre-emptively ahead of any traffic. Likewise, nothing gets redone between users. Since http traffic is essentially disconnected, there is no way of knowing for sure when a user has gone away. Web servers often have recycle / shutdown criteria, but that is again largely unrelated to users.

Life cycle of a web application:

  • at some point it starts, perhaps spontaneously, perhaps due to an incoming request, perhaps as part of app-pool cycling
  • it services lots of http requests from lots of different users; often concurrently, and often interleaved
  • at some point, it shuts down; perhaps due to inactivity, perhaps due to app-pool cyclying, perhaps due to a server shutdown

There is no special life-cycle here that relates to users. All you can see from the web-server perspective are individual requests, and they only last as long as it takes for you to respond to them. You don't know when they close their browser, nor do you know that they've left the tab open on their browser and gone on holiday for a week.

There are ways of knowing more about this, but they aren't directly web-server concerns, and they certainly should not tie into any controller member state. If it impacts controller state: you are doing it wrong.

OTHER TIPS

One can do the following in the controller index() method for the "home" page of the application (which is always visited when a new user enters the app):

Our app tracks logged in users, therefore one can track the old user with a static variable, and when this changes, run "initialization" on the other static variables, and finally set the one tracking users to the new user. This works for what I'm trying to accomplish.

NOTE: We don't have a highly-transactional system, there are only a few users and shouldn't be that many occasions of multiple users at once. If there were, this might become a mess!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top