2012-01-27 54 views
-1

在經典的Passive-MVP模式,我如何避免在我看來完全主持人的參考&仍注入演示者實例需要視圖實例作爲參數。我如何注入主持人到一個視圖沒有參考主持人

用asp.net爲例:

  • 我實現的觀點(網絡工程)不應該有演示者的參考。 (無論是IPresenter還是具體的)
  • 當視圖實例化時,(基本上是我的網頁),演示者應該用當前視圖的引用實例化。
  • 我使用unity作爲我的ioc容器。

現在我在網頁的代碼做的背後是這樣的:

public partial class SomePage : MyBasePage, ISomeView 
{ 
    private readonly ISomePresenter presenter; 

    public SomePage() 
    { 
     this.presenter = ResolveSomeWay(this); 
    } 
} 

爲了這個,我有一個參考,我認爲實行「主講合同DLL」。有沒有一種方法可以完全避免這個引用&仍然與視圖實例掛鉤的主持人,當視圖實例化?

我只關心演示者實例化,因爲演示者的構造函數可以將傳遞的參數視圖實例設置爲它的視圖屬性&它訂閱視圖的事件,以用於任何未來的通信。

謝謝你們的時間。

回答

0

你可以「發佈」一個新的View被實例化爲一個消息總線,Presenter工廠可以將實例化的View「綁定」到一個Presenter。儘管視圖對主持人不可知,但它不是消息總線。

public partial class SomePage : MyBasePage, ISomeView 
{ 
    // Alternative #1 
    public SomePage(IMessageBus messageBus) 
    { 
     // You publish a message saying that a handler for ISomeView is to handle the 
     // message. 
     messageBus.Publish<ISomeView>(this); 
    } 
    // Alternative #2 
    public SomePage() 
    { 
     Resolver.Resolve<IMessageBus>().Publish<ISomeView>(this); 
    } 
} 

// This could be somewhere else in your application (this could be a separate DLL), but 
// I will use the Global.asax.cs here, for simplicity 
public void Application_Start() 
{ 
    Container.Resolve<IMessageBus>() 
      .Subscribe<ISomeView>(someView => 
       { 
        var presenter = new SomePresenter(someView); 
       }); 
} 

public interface ISomeView { 
    event Action<ISomeView> SomeEvent; 
} 

public class SomePresenter 
{ 
    public SomePresenter(ISomeView view) { 
     // if you attach the presenter to the View event, 
     // the Garbage Collector won't finalize the Presenter until 
     // the View is finalized too 
     view.SomeEvent += SomeEventHandler; 
    } 

    private void SomeEventHandler(ISomeView view) { 
     // handle the event 
    } 
} 
+0

謝謝馬塞爾。我結束了遵循確切的第二種方法..有一個解決方案DLL,基本上在整個解決方案IoC。因此解析器具有對Presenter接口的引用。 Resolver.ResolvePresenter (this); – 2012-06-27 18:44:35

+0

有IoC /依賴注入容器,允許您從容器本身刪除依賴項。你只需要定義構造函數,並且依賴注入容器爲對象提供一個實例,結帳:Ninject,StructureMap,Windsor Container和Microsoft Unity Container。 Unity容器是可擴展的,可以用任何其他容器代替。 – 2012-07-09 00:39:36