views:

1954

answers:

3

I am trying to perform some actions at the end of every request. I changed the Application_Start() that is generated when created new project to make a test:

protected void Application_Start()
    {
        EndRequest += (s, e) =>
        {
            Console.Write("fghfgh");
        };
        RegisterRoutes(RouteTable.Routes);

    }

The lambda won't get called. Any ideas why?

edit: I see that they are doing similar thing in SharpArch [http://code.google.com/p/sharp-architecture/] and it does work there... And no, I don't want to use an HttpModule.

edit2: The only workaround I found is to use Application_EndRequest in conjuction with a private static member of global.asax:

private static WebSessionStorage wss;
protected void Application_Start()
{
    //...
    wss = new WebSessionStorage(this);
    //...
}

protected void Application_EndRequest(object sender, EventArgs e)
{
    wss.EndRequest(sender, e);
}

wss must be private because it seems like the Application_EndRequest is being called using different instance object (this). That may also be reason of my event (as described at the beginning) not being called.

+2  A: 

I usually do:

protected void Application_EndRequest(object sender, EventArgs e)
{
}

This works as excepted. Don't know about the event though.

Jabe
I actually pass the this instance to some object, that in turn hooks with its own handler. So I can't user the Application_EndRequest.
What are you passing in?
Daniel A. White
in Application_Start I'm doing: NHSession.Init(new WebSessionStorage(this));The WebSessionManager hooks in its ctor: public WebSessionStorage(HttpApplication app) { app.EndRequest += Application_EndRequest; }
+1  A: 

Your best bet is to do this in an HttpModule. I use an HttpModule to manage NHibernate session in an MVC app and it works perfectly. In the begin request I bind the sessionFactory to the ManagedWebSessionContext (in NHibernate but fairly undocumented) and then in the end request I commit any transactions and unbind the sessionFactory.

I think it is cleaner to separate this into an HttpModule as well.

James Avery
A: 

The HttpApplication instance that is represented by your global.asax file is a single instance that only represents the first HttpApplication object. It is not guaranteed that this instance of the HttpApplication will be used for any other request.

You need to override the Init() method in global.asax and in that method hook up any events that you want:

public override void Init() {
    base.Init();

    EndRequest += MyEventHandler;
}

Please refer to this MSDN article for more info on the HttpApplication object.

Eilon