Search code examples
sharepointsharepoint-2007global-asaxapplication-start

How can you hook a SharePoint 2007 feature into the Application_Start of a site?


I was wondering if there is a good way to hook into the Application_Start of a SharePoint 2007 site when developing a feature? I know I can directly edit the Global.asax file in the site root, but is there a way to do this so that it gets deployed with the feature?

Thanks!


Solution

  • This is actually possible, but it doesn't involve the Global.asax file.

    Many of Microsoft's examples demonstrate wiring code in via the Global.asax, but this is not a best-practices approach when it comes to SharePoint. Ideally, your code should get packaged as a Feature and deployed via WSP (as you already know).

    The key lies in implementing the code in question as an HttpModule (i.e., a type that implements the IHttpModule interface) and wiring it into the ASP.NET pipeline servicing your SharePoint application. Roughly speaking, these are the steps:

    1. Create a class that implements the IHttpModule interface.
    2. Implement the Init method in your HttpModule; this is called when the HttpApplication (in this case, the SPHttpApplication) is setup, and it gives you an opportunity to carry out processing, wire-up event delegates for other pipeline events, etc.
    3. Create an SPFeatureReceiver that will add and remove your HttpModule from target web.config files on activation and deactivation, respectively. This is carried out using the SPWebConfigModification type to update the <httpModules> node in target web.config files.
    4. Package all as a Feature and deploy via WSP.

    For more information on HttpModule development, see http://msdn.microsoft.com/en-us/library/ms227673.aspx. For some additional detail on the SPWebConfigModification type, see http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebconfigmodification.aspx.

    Result: a class that can handle application startup and is deployable via Feature. No manual file hacking required.

    I've successfully used this in a number of scenarios -- most recently with a custom caching provider (IVaryByCustomHandler) that needed to register itself for callbacks with the SPHttpApplication when it started.

    Though your question is a bit older, I hope this helps!