Alex from Jitbit
Alex from Jitbit

Reputation: 60812

Handling application-wide events without Global.asax

My project has no "global.asax" for various reasons and I can't change that (it's a component). Also, I have no access to web.config, so an httpModule is also not an option.

Is there a way to handle application-wide events, like "BeginRequest" in this case?

I tried this and it didn't work, can someone explain why? Seems like a bug:

HttpContext.Current.ApplicationInstance.BeginRequest += MyStaticMethod;

Upvotes: 7

Views: 2219

Answers (1)

Oleks
Oleks

Reputation: 32343

No, this is not a bug. Event handlers can only be bound to HttpApplication events during IHttpModule initialization and you're trying to add it somewhere in the Page_Init(my assumption).

So you need to register a http module with desired event handlers dynamically. If you're under .NET 4 there is a good news for you - there is PreApplicationStartMethodAttribute attribute (a reference: Three Hidden Extensibility Gems in ASP.NET 4):

This new attribute allows you to have code run way early in the ASP.NET pipeline as an application starts up. I mean way early, even before Application_Start.

So the things left are pretty simple: you need to create your own http module with event handlers you want, module initializer and attribute to your AssemblyInfo.cs file . Here is a module example:

public class MyModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
    }

    public void Dispose()
    {

    }

    void context_BeginRequest(object sender, EventArgs e)
    {

    }
}

To register module dynamically you could use DynamicModuleUtility.RegisterModule method from the Microsoft.Web.Infrastructure.dll assembly:

public class Initializer
{
    public static void Initialize()
    {
        DynamicModuleUtility.RegisterModule(typeof(MyModule));
    }
}

the only thing left is to add the necessary attribute to your AssemblyInfo.cs:

[assembly: PreApplicationStartMethod(typeof(Initializer), "Initialize")]

Upvotes: 11

Related Questions