代码之家  ›  专栏  ›  技术社区  ›  blu

ASP.NET MVP注入服务依赖项

  •  4
  • blu  · 技术社区  · 16 年前

    Phil Haack's post providing was used as the starting point ,我将从文章中举出一些例子来说明这个问题。

    public partial class _Default : System.Web.UI.Page, IPostEditView {
    
        PostEditController controller;
        public _Default()
        {
             this.controller = new PostEditController(this, new BlogDataService());
        }
    }
    

    但是,我更喜欢使用构造函数方法进行测试。

    3 回复  |  直到 16 年前
        1
  •  1
  •   Neil Barnwell    16 年前

    如果你使用 Microsoft ServiceLocator ,你可以申请 service locator design pattern

    在您的情况下,它看起来像这样:

    public partial class _Default : System.Web.UI.Page, IPostEditView {
    
        PostEditController controller;
        public _Default()
        {
             var service = ServiceLocator.Current.GetInstance<IBlogDataService>();
             this.controller = new PostEditController(this, service);
        }
    }
    

        2
  •  2
  •   Kenny Eliasson    16 年前

    在我们自己开发的MVP框架中,我们有一个类型化基类,所有页面都继承自该基类。需要的类型为Presenter类型(我们的基本Presenter类)

    在基类中,我们使用IoC容器初始化了控制器。

    示例代码:

    public class EditPage : BasePage<EditController> {
    }
    
    public class EditController : Presenter {
     public EditController(IService service) { }
    }
    
    public class BasePage<T> : Page where T: Presenter
    {
     T Presenter { get; set; }
     public BasePage() { 
      Presenter = ObjectFactory.GetInstance<T>(); //StructureMap
     }
    }
    

        3
  •  1
  •   Philip Rieck    16 年前

    然而, autofac (我非常喜欢的DI容器)有一个 integration module for ASP.NET WebForms

    public partial class _Default : System.Web.UI.Page, IPostEditView {
    
        public IBlogDataService DataService{get;set;}
        public _Default()
        {
        }
    }
    

    我知道这并没有特别解决您使用构造函数注入的愿望,但这是我所知道的最接近的。