我已经实现了我自己的模型视图演示者模式的副本(在Web客户端软件工厂的静脉中),所以我可以利用我自己的DI框架而不是绑定到WCSF的ObjectBuilder,我遇到了很多问题.我想出了几个方法来做到这一点,但没有一个特别让我开心.我想知道是否有其他人有其他想法.
使用HttpModule拦截context.PreRequestHandlerExecute来调用ObjectFactory.BuildUp(HttpContext.Current.Handler)
public partial class _Default : Page, IEmployeeView { private EmployeePresenter _presenter; private EmployeePresenter Presenter { set { _presenter = value; _presenter.View = this; } } }
在页面加载中调用buildup而不是使用HttpModule
public partial class _Default : Page, IEmployeeView { private EmployeePresenter _presenter; private EmployeePresenter Presenter { set { _presenter = value; _presenter.View = this; } } protected void Page_Load(object sender, EventArgs e) { ObjectFactory.BuildUp(this); } }
如果需要,通过Property访问presenter允许Getter to BuildUp.
public partial class _Default : Page, IEmployeeView { private EmployeePresenter _presenter; public EmployeePresenter Presenter { get { if (_presenter == null) { ObjectFactory.BuildUp(this); } return _presenter; } set { _presenter = value; _presenter.View = this; } } }
public partial class _Default : Page, IEmployeeView { private EmployeePresenter _presenter; private EmployeePresenter Presenter { get { if (_presenter == null) { _presenter = ObjectFactory.GetInstance(); _presenter.View = this; } return _presenter; } } }
public partial class _Default : Page, IEmployeeView { private EmployeePresenter _presenter; private EmployeePresenter Presenter { get { if (_presenter == null) { Presenter = ObjectFactory.GetInstance(); } return _presenter; } set { _presenter = value; _presenter.View = this; } } }
编辑:添加解决方案1c,2b
我将使用解决方案#1b,并为所有页面创建一个图层超类型,以便更多地干预演示者初始化.像这样:
页码:
public partial class _Default : AbstractPage, IEmployeeView { private EmployeePresenter presenter; private EmployeePresenter Presenter { set { presenter = value; presenter.View = this; } } protected override void Do_Load(object sender, EventArgs args) { //do "on load" stuff } }
摘要页码:
public abstract class AbstractPage : Page { protected void Page_Load(object sender, EventArgs e) { ObjectFactory.BuildUp(this); this.Do_Load(sender,e); //template method, to enable subclasses to mimic "Page_load" event } //Default Implementation (do nothing) protected virtual void Do_Load(object sender, EventArgs e){} }
使用此解决方案,您只能在一个类中进行演示者初始化(由ObjectFactory创建),如果您以后需要对其进行修改,则可以轻松完成.
编辑:
Do_Load应该是抽象的还是虚拟的?
Template Method最初声明该方法应该是Abstract,以强制子类实现它,遵守超类契约.(参见维基百科"垄断"<"游戏"的例子).
另一方面,在这种特殊情况下,我们不希望强制用户类重新定义我们的方法,但给它机会这样做.如果你声明它是抽象的,许多类将被迫重新定义方法只是为了让它为空(这显然是代码味道).所以我们提供合理的默认值(什么都不做)并使方法成为虚拟的.