在实现MVP模式时使用ObjectBuilder时出现NullReferenceException

时间:2010-03-10 06:49:06

标签: c# mvp

我正在我的应用程序中实现MVP模式。 但我在我的视图类的Page_Load上得到NullReferenceException。 这是我的演讲者课程:

using Microsoft.Practices.CompositeWeb;

namespace PresenterDLL
{
    public class NamePresenter : Presenter<IProduct>
    {
        public void  SayHello()
        {
            View.Name = 200;            
        }
    }

    public interface IProduct
    {
        int Name { get; set; }
    }
}

这是我观点背后的代码:

使用System; 使用PresenterDLL; 使用Microsoft.Practices.ObjectBuilder;

public partial class _Default:BasePage,IProduct {     private NamePresenter _presenter;

[CreateNew]
public NamePresenter Presenter
{
    set
    {
        this._presenter = value;
        _presenter.View = this;
    }
}

protected void Page_Load(object sender, EventArgs e)
{


    if (!IsPostBack)
    {
        this._presenter.OnViewInitialized();
        this._presenter.SayHello();
    }

    this._presenter.OnViewLoaded();
}

public int Name
{
    get
    {
        return 10;
    }
    set
    {
        TextBox1.Text = value.ToString();
    }
}

}

在运行应用程序时,我在Page_Load方法中得到NullreferenceException, 因为_presenter为null。因为它从未被调用过。那么,我应该怎么做才能让ObjectBuilder在页面生命周期开始之前调用它。

我的基页类是:

public class BasePage : Microsoft.Practices.CompositeWeb.Web.UI.Page
    {
      public BasePage()
          : base()
      {

          // _ctlForm = this;
          //    WebClientApplication.BuildItemWithCurrentContext(this);
      }

      protected override void OnInit(EventArgs e)
      {      

          base.OnInit(e);
          //Disable all caching
          Response.CacheControl = "no-cache";
          Response.AddHeader("Pragma", "no-cache");
          Response.Expires = -1;          
      }

      protected override void OnPreInit(EventArgs e)
      {
          //This has been moved to the top since the preinit in the base clase is responsible
          //for dependency injections.

          //ObjectFactory.BuildUp(this); 

          base.OnPreInit(e);
      }

      protected override void OnPreRender(EventArgs e)
      {  

          base.OnPreRender(e);
      }

    }

有人可以找出问题出在哪里......

1 个答案:

答案 0 :(得分:0)

我认为您可能遇到以下两个问题之一:Presenter属性的setter根本没有被调用,或者被调用但是分配了null。我认为你应该尝试在Presenter属性的setter中设置一个断点,看看发生了什么。

您可以尝试覆盖PreInit(http://dotnetchris.wordpress.com/2009/02/16/creating-a-generic-model-view-presenter-framework/):

protected override void OnPreInit(EventArgs e)
{
    ObjectFactory.BuildUp(this);
    base.OnPreInit(e);
}