继承Global.asax和Application_Start问题

时间:2012-11-28 12:37:03

标签: c# asp.net global-asax

我正在尝试继承一个基本的global.asax类来创建我的自定义global.asax类。但我的客户继承全球课不能正常工作。它的Application_Start不会被调用。

谁知道乳清?

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#" %>

在日志文件中,我找不到“Portal started 2”,但只找到“Portal Started”。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

在启动应用程序时,运行时采用HttpApplication文件指出的Global.asax后代,并创建它的实例。运行时不知道或关心类是如何从HttpApplication继承下来的,它只关心它实际上是后代。

之后,它开始调用方法,将其视为常规HttpApplication对象。由于new修饰符有效地破坏了继承链(它只是一个碰巧共享旧方法名称的新方法),因此不会调用它,而是调用父类的方法。基本上你有这种情况(伪代码):

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

这是脆弱的基类问题的一个例子和结果,一个关于Eric Lippert has written in depth的主题。

答案 1 :(得分:1)

解决方案是在基类中声明虚函数,然后在子类中重写它。

但由于您无法编辑基类以将Application_Start方法声明为虚拟,因此它不起作用: Is it possible to override a non-virtual method?

接受的答案给出了一个符合您案例的例子。