Applying Dependency Injection on an ASP.NET web forms application built using MVP Pattern

这一生的挚爱 提交于 2019-12-06 02:31:10

To solve this problem you could use property injection.

First, register ShipperOperations, Navigator and ShipperPresenter in the DI container.

Then, in the Page_Load method of your view, invoke the resolve method of the DI container of your choice.

public class ShipperPresenter
{
        IShipper shipperView;
        IShipperOperations operations;
        INavigator navigator;
        public ShipperPresenter(IShipperOperations operations,INavigator navigator)
        {
            this.operations = operations;
            this.navigator = navigator;
        }

        public IShipper ShipperView
        {
            get { return shipperView; }
            set { shipperView = value; }
        }
        ...
}

And the view would look like this:

public partial class ShipperView : System.Web.UI.Page, IShipperView
{
       ShipperPresenter presenter;

       protected void Page_Load(object sender, EventArgs e)
       {
           presenter = YourIOC.Resolve<ShipperPresenter>();
           presenter.ShipperView = this;
       }
       ...
}

You could also use a factory to create the presenter at runtime, while passing it the parameters of your choice. In fact, in a DI world, this is THE way to proceed when you want to instantiate objects with dependencies that are only known at runtime. There is a nice mechanism for this in Castle Windsor, it's called typed factories.

Using a factory, no need to modify the presenter class. Instead, create an interface for the factory:

public interface IShipperPresenterFactory
{
    ShipperPresenter Create(IShipper shipperView);
}

If using Windsor, the only thing that you have to do is to register this interface as a typed factory. With other DI containers, you will have to implement a class that uses the DI container internally to resolve the presenter.

The Page_Load method of the view would then use the factory like this:

protected void Page_Load(object sender, EventArgs e)
{
    var factory = YourIOC.Resolve<IShipperPresenterFactory>();
    presenter = factory.Create(this);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!