How to handle Application_End event from outside global.asax
We can attach to this event from global.asax file creating method with name Application_End(). But I need to attach to it like this
HttpContext.ApplicationInstance.A开发者_开发问答pplicationEnd+=OnApplicationEnd;
Is there any way to do it?
Have solved the problem in such way.
public class MyHttpApplication:HttpApplication
{
public event Action ApplicationEnd;
protected void Application_End()
{
if (ApplicationEnd != null)
ApplicationEnd();
}
}
In global.asax defined
<%@ Application Inherits="MyLib.MyHttpApplication" Language="C#" %>
Then in code
var app = HttpContext.ApplicationInstance as MyHttpApplication;
app.ApplicationEnd += () => { // do something };
Application_End is a special "event" that is called by Asp.net that doesn't belog to the HttpApplication class.
From MSDN *The Application_Start and Application_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance.*
I think you can have the same behaviour attaching and handler to the AppDomain.DomainUnload event
//your global.asax class contrauctor
public GlobalApplication()
{
AppDomain.CurrentDomain.DomainUnload += ApplicationEnd;
}
private void ApplicationEnd(object sender, EventArgs e)
{
}
I know the answer is already given but wanted to also include this way:
[assembly: PreApplicationStartMethod(typeof(Bootstraper), "Start")]
[assembly: ApplicationShutdownMethod(typeof(Bootstraper), "End")]
public static class Bootstraper
{
public static void End()
{
...
}
public static void Start()
{
...
}
}
精彩评论