2012-01-27 58 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