views:

264

answers:

3

I’m implementing a simple HttpModule, where I want some code to run when the web application is started. But I’m surprised to find that the Application_Start event I would normally use from Global.asax is not available from a HttpModule. Is that correct, or am I missing something here?

How do I hook into the Application_Start event from an HttpModule?

Update:
I’ve come to simple solution using the Init event instead, but it still smells a bit funny to me.

+1  A: 

You cannot attach to the Application_Start event in an HttpModule. Here's a list of available events.

Darin Dimitrov
Hmm, that's what I feared. Do I have any other options for creating a reusable library that can be deployed on existing web applications by simply adding a dll and a few web.config changes?
Jakob Gade
What is this *reusable library* supposed to do?
Darin Dimitrov
It sends out a notification that the web application has started.
Jakob Gade
+1  A: 

I agree with Darin.

the reason being that the application needs to be loaded in order to load modules, so how can you execute code within module before the application is ready to begin loading the module itself?

What are you trying to do? Might be worth evaluating what the idea of your solution looks like :)

Hope this helps :)

Wardy
Shouldn't there be a "I'm ready" event at least then, which fires when all the modules have been loaded and the app is up and running? I was trying to send out a notification to a remote server to indicate the site had been (re-)loaded.
Jakob Gade
+1  A: 

You CAN use HttpModule to handle application start event

Contrary to others that only write/believe what they read I've done my own part and found out it's possible to handle Application start using an HTTP module. It's a bit of a hack really but it reliably works. It's not simething someone should avoid, because I've seen it in MS modules as well (namely Sharepoint 2010 SPRequestModule) This blog post will get you started. I've done it myself and it simply works.

If you want it to be thread safe as well, you can also lock execution and then mark module as application started. It's the safest way of doing it.

private static bool isStarted = false;
private static object moduleStart = new Object();
...
if (!isStarted)
{
    lock(moduleStart)
    {
        if (!isStarted)
        {
            // handle aplication start
            ...
            isStarted = true;
        }
    }
}

I've created my own library that hooks to existing applications like Sharepoint 2010. I don't want to change Global.asax of Sharepoint now do I? Using technique explained in the blog post, I was able to hook into it. Easily.

And I guess this is exactly what you've been looking for. Hooking inot start event of an arbitrary application by adding a module into web.config. Do it this way. It will work.

Robert Koritnik