3

According to this answer, ASP.NET MVC creates a new instance of the controller class to respond to each request.

My question is, when does the controller instance get destroyed?

So far, I've been assuming (perhaps incorrectly) that these instances are destroyed at the end of each response, but some database pool issues I'm having lead me to think that perhaps they are left for the garbage collector. Does anyone have any insights on this?

tereško
  • 58,060
  • 25
  • 98
  • 150
Mark Micallef
  • 2,643
  • 7
  • 28
  • 36
  • 2
    also see this http://stackoverflow.com/questions/2355139/what-is-the-lifetime-of-a-asp-net-mvc-controller – user786 Aug 04 '15 at 04:54
  • that's why you should create your resources rather in your actions (and of course clean them up - most likely by *using* `using` ;) ) – Random Dev Aug 04 '15 at 05:01

1 Answers1

6

The controller is left to be cleaned up by the garbage collector. But if you were to issue a new request before the old controller is cleaned up it should not affect your new request since a new controller with a fresh context will be created for that new request.

If you are having DB issues, it may come from how you handle reading/writing to the DB on your back-end. A DB context 'A' is not aware of the changes happening in another DB context 'B' if A was instantiated before changes in B took place. Not sure if that is the problem you are getting though.

Sami Awwad
  • 373
  • 2
  • 8
  • Thanks Sami. Is there a way to execute some code at the end of the page lifecycle (after the controller method executes), without putting the logic into each method? I need to ensure that all resources are released, especially any database connections. – Mark Micallef Aug 04 '15 at 05:13
  • @MarkyMark Your DB connection should be released automatically when the code execution involving your connection goes out of scope. This link may help (I assume you are using the Entity Framework) [Connection Management](https://msdn.microsoft.com/en-us/data/dn456849.aspx) – Sami Awwad Aug 04 '15 at 05:20
  • 3
    I believe I've found the answer to my own question, which is to override the OnResultExecuted() method. This allows me to execute some code after the controller method has finished executing, without waiting for the garbage collector to release resources. – Mark Micallef Aug 04 '15 at 05:27