MVP依赖注入 [英] MVP dependency injection

查看:205
本文介绍了MVP依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常你为每个视图创建演示,并通过视图插入构造函数中的主持人。但是,如果您有:

normally you create a presenter for each view and pass the view into the presenter on constructor. But what if you have:


  1. 多个意见需要听取他们对事件服务

  2. 多个视图都指向同一个数据模型的缓存。

有人可以显示信息来自用户的点击来正常流动数据早在从服务器服务

can someone display a normal flow of info from a user click to data coming back in a service from a server.

推荐答案

下面是我做的:

首先,我定义论文接口:

First, I define theses interfaces:

public interface IView<TPresenter>
{
    TPresenter Presenter { get; set; }
}

public interface IPresenter<TView, TPresenter>
    where TView : IView<TPresenter>
    where TPresenter : IPresenter<TView, TPresenter>
{
    TView View { get; set; }
}



然后这个抽象主持人类:

Then this abstract presenter class:

public abstract class AbstractPresenter<TView, TPresenter> : IPresenter<TView, TPresenter>
    where TView : IView<TPresenter>
    where TPresenter : class, IPresenter<TView, TPresenter>
{
    protected TView view;

    public TView View
    {
        get { return this.view; }
        set
        {
            this.view = value;
            this.view.Presenter = this as TPresenter;
        }
    }
}



该视图通过注入物业,而不是构造函数,允许在二传手双向感情。请注意,需要一个安全的投...

The view is injected via a property, instead of the constructor, to allow the bi-directional affection in the setter. Notice that a safe cast is needed...

然后,我具体的主持人是这样的:

Then, my concrete presenter is something like :

public class MyPresenter : AbstractPresenter<IMyView, MyPresenter>
{
    //...
}



其中 IMyView 工具 IVIEW 。一个具体的视图类型必须存在(如 MyView的),但它是解决它的容器:

Where IMyView implements IView. A concrete view type must exists (e.g. MyView), but it's the container that resolves it:


  1. 我注册 MyPresenter 中的容器类型为本身具有瞬态行为。

  2. 我注册 MyView的 IMyView 在一个短暂的行为的容器。

  3. 然后我要求一个 MyPresenter 到容器中。

  4. 集装箱实例化一个MyView的

  5. 这instanciates一个 MyPresenter

  6. 它注入到视图通过 AbstractPresenter.View 属性中的主持人。

  7. 的二传手代码完成双向关联

  8. 的容器返回夫妇演示/查看

  1. I register MyPresenter type as itself in the container, with a transient behavior.
  2. I register MyView as an IMyView in the container with a transient behavior.
  3. I then asks for a MyPresenter to the container.
  4. Container instanciate a MyView
  5. It instanciates a MyPresenter
  6. It inject the view into the presenter through the AbstractPresenter.View property.
  7. The setter code completes the bi-directional association
  8. The container returns the couple Presenter/View

它可以让你注入其他依赖(服务,回购)到两个视图和您的主持人。但是,在您所描述的情况,我建议你注射服务和缓存到主持人,而不是视图。

It allows you to inject other dependencies (services, repos) into both your view and your presenter. But in the scenario you described, I recommend you to inject services and caches into the presenter, instead of the view.

这篇关于MVP依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆