ValidfroM
ValidfroM

Reputation: 2817

Inherited Global.asax and Application_Start issue

I am trying to inherite a base global.asax class to create my custom global.asax class. But my custome inherited global class does not work properly. Its Application_Start wont been called.

Anyone knows whey?

public class BaseGlobal : HttpApplication
{
    protected void Application_Start(Object sender, EventArgs e)
    {
        log4net.Config.XmlConfigurator.Configure();
        Logger.Warn("Portal Started");  //I can find it log file
    }
    ......
}


public class MyGlobal : BaseGlobal
{
        new protected void Application_Start(Object sender, EventArgs e)
        {
            base.Application_Start(sender,e);

            Logger.Warn("Portal Started 2"); // Can not find it in log file
        }
}


<%@ Application Codebehind="Global.asax.cs" Inherits="Membership_ABC.MyGlobal" Language="C#" %>

In the log file, I could not find "Portal started 2" but just "Portal Started".

Any ideas?

Upvotes: 3

Views: 5157

Answers (2)

AlexH
AlexH

Reputation: 2700

The solution is to declare the function virtual in the base class and then override it in the child class.

But as you can't edit base class to declare the Application_Start method virtual, it won't work : Is it possible to override a non-virtual method?

The accepted answer gives an example that matches your case.

Upvotes: 1

SWeko
SWeko

Reputation: 30882

On startup of an application, the runtime takes the HttpApplication descendant that is pointed out by the Global.asax file, and creates an instance of it. The runtime does not know or care how the class got to be descended from HttpApplication, it just cares that it is, in fact a descendant.

After that it start calling method on it, treating it as a regular HttpApplication object. Since the new modifier effectively breaks the inheritance chain (it's just a new method that happens to share the old methods name) it is not called, but instead the method of the parent class is called. Basically you have this situation (pseudocode):

HttpApplication httpApp = new MyGlobal();
httpApp.Application_Start(..) 
// ^^^ calls BaseGlobal.Application_Start(..)
//because the is not an unbroken chain from HttpApplication to MyGlobal

This is an example and consequence of the Brittle Base Class problem, a topic about which Eric Lippert has written in depth.

Upvotes: 3

Related Questions