MVP dependency injection

后端 未结 4 1660
终归单人心
终归单人心 2021-01-30 18:45

using MVP, what is the normal order of construction and dependency injection.

normally you create a presenter for each view and pass the view into the presenter on const

4条回答
  •  深忆病人
    2021-01-30 19:35

    Here is what I do:

    First, I define theses interfaces:

    public interface IView
    {
        TPresenter Presenter { get; set; }
    }
    
    public interface IPresenter
        where TView : IView
        where TPresenter : IPresenter
    {
        TView View { get; set; }
    }
    

    Then this abstract presenter class:

    public abstract class AbstractPresenter : IPresenter
        where TView : IView
        where TPresenter : class, IPresenter
    {
        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
    {
        //...
    }
    

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

    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.

提交回复
热议问题