2010-03-10 50 views
0

我在應用程序中實現了MVP模式。 但我在我的視圖類的Page_Load上得到NullReferenceException。 這裏是我的演講類:在使用ObjectBuilder實現MVP模式時使用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; } 
    } 
} 

,這裏是隱藏類我的看法代碼:

使用系統; 使用PresenterDLL; using 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空。因爲它從來沒有被調用。所以,我應該怎麼做才能讓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); 
     } 

    } 

是否有人可以找出問題出在哪裏?

+0

更換_Default:System.Web.UI.Page到_DEFAULT:PageBase(我不記得基地頁面的名稱,而是使用一些基本頁面從框架) – garik 2010-03-10 08:32:06

回答

0

我想你可能會遇到以下兩個問題之一:Presenter屬性的setter根本沒有被調用,或者它被調用,但分配了null。我想你應該試着在Presenter屬性的設置者中設置一個斷點來看看發生了什麼。

你可以嘗試重寫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); 
} 
+0

是的,它從來沒有被稱爲...我需要做什麼,以便它可以被稱爲.... – 2010-03-10 08:24:24

+0

嘗試調用ObjectFactory.BuildUp方法(我用例子更新了我的答案)。 – 2010-03-10 08:59:59

+0

其中是ObjectFactory類的定義,我的意思是在哪個命名空間? – 2010-03-11 04:36:59