Well - exactly as the question subject states - any ideas on how you might do this?
I've been looking over the objects in System.Web.Hosting but nothing is standing out.
The reason? I'm getting one or two application errors which are typically occuring during a recycle (they happen about 25 hours apart and I've left my app pool recycle time at the default) and so I want to know if they're happening on a thread that's in the pool that's shutting down, or the one that's start(ed/ing) up.
I recently stumbled across this article on Brain.Save() which talks about exactly this issue from the point of view of hosting WCF (he's Steve Maine - A program manager at Redmond on the Connected Servies Division).
They need to be able to do this when a WCF service is hosted inside Asp.Net since they need to be able to shutdown any open listeners so that the WCF engine in the new app domain will be able to open them all up again.
As the article demonstrates, the answer is to implement the IRegisteredObject interface, call
ApplicationManager.CreateObject
to create an instance of your object and then register it withHostingEnvironment.RegisterObject
(all detailed in the MSDN documentation for the interface).When this object's
IRegisteredObject.Stop(bool)
implementation is called withfalse
as the parameter, this is notification that the app domain is being shut down and that the object should be unregistered (kind of like a global dispose) with a call toHostingEnvironment.UnregisterObject
.When it's called with
true
it means you've not unregistered in good time, and that if you don't Unregister immediately, it'll be done for you.I can certainly use this mechanism to find out, when an exception occurs, if the AppDomain is being killed or not. The nature of the object in question that throws the exception means that if it's not at shutdown, it must be during initial startup.
Equally, however, I may well start looking at this persistence mechanism for some of my other more complicated static information!
The History
The article also explains some of the history, and rationale, of why you would want to use
IRegisteredObject
rather than Application_Start and Application_End methods inglobal.asax
:Not sure exactly what you want to do when the appication pool recycles but if you add the below event handler to Global.asax then the code in it will run when the application is shut down.
You can check the value of System.Web.Hosting.HostingEnvironment.ShutdownReason, when the app pool is not in the process of closing / recycling it will have the ShutdownReason of None.
Adding the actual code to do this:
Then enable it by running
After that just check that property for IsRecycling to know if you are recyling or not.