I have a library class used in ASP.Net and non-web applications that needs end-of-application finalization.
Within my project's library, I want the class to do its own end-of-application finalization without requiring a developer to add a call to Global.Application_End or AppDomain.CurrentDomain.ProcessExit.
How can this be done?
Additional background/rationale:
Even if I were to consider those options, it appears that AppDomain.CurrentDomain.ProcessExit does not get called when an ASP .Net application is stopped in IIS. And Global.Application_End is specific to ASP .Net. So, neither option is compatible with both situations.
If it helps to have a specific example of why this might be needed... In this particular case, it uses SqlDependency which (as I understand it) requires a call to SqlDependency.Start for initialization and a call to SqlDependency.Stop before application termination.
It appears that a simulated static fianalizer described in this S.O. answer, https://stackoverflow.com/a/256278/449837, works in both web and non-web applications.
Here's a sample that I have working:
public class ClassThatNeedsStaticFinalizer {
// ... other class properties, methods, etc ...
#region Static Finalizer Emulation
static readonly Finalizer finalizer = new Finalizer();
private sealed class Finalizer
{
~Finalizer()
{
// ... Do final stuff here ...
}
}
#endregion
}
(NOTE: For some code scratchpad environments like LinqPad, ~Finalizer may not fire until the scratchpad app itself closes)