Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wiring up the Page_PreInit event manually, with AutoEventWireup set to false

If the AutoEventWireup attribute is set to false, the events need to be wired up manually. However, I cannot seem to get the Page_PreInit to fire. I would guess that I might be making the wireup happen too late (once we're already past Page_PreInit), but I'm not sure where else to put the wireups.

For example...

protected override void OnInit(EventArgs e)
{
    base.OnInit(e)
    PreInit += new EventHandler(Page_PreInit);
    Load += new EventHandler(Page_Load);
}

protected void Page_PreInit(object sender, EventArgs e)
{
    Response.Write("Page_PreInit event fired!<br>");  //this is never reached
}

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write("Page_Load event fired!<br>");
}

The above code results in "Page_Load event fired!" being displayed, but nothing from Page_PreInit. I tried base.OnInit(e) both before AND after the wireups, and that had no effect.

The graph shown here says that the OnInit method actually comes after the PreInit event. With that in mind, I tried overriding OnPreInit and doing the same thing --- no effect.

The MSDN article here explicitly says that in the event of AutoEventWireup set to false, the events can be wired up in an overriden OnInit. The example they use is Page_Load, and of course that works just like it does for me, but they don't address that this doesn't seem to work for the Page_PreInit event.

My question is: how can I get the Page_PreInit event wired up in the case of AutoEventWireup set to false?

I understand there are alternatives as listed on the MSDN page, such as using the page's constructor. I'd like to know specifically how to do like they suggest with OnInit.

like image 785
CptSupermrkt Avatar asked Aug 07 '12 07:08

CptSupermrkt


1 Answers

The base implementation of the OnPreInit() method is responsible for raising the PreInit event. Since your override calls that implementation before registering your PreInit handler, it will indeed not be called.

Try calling the base class' method after registering the handler:

protected override void OnPreInit(EventArgs e)
{
    PreInit += new EventHandler(Page_PreInit);
    Load += new EventHandler(Page_Load);

    // And only then:
    base.OnPreInit(e);
}
like image 122
Frédéric Hamidi Avatar answered Sep 20 '22 09:09

Frédéric Hamidi