ASP.NET MVP注入服务依赖关系 [英] ASP.NET MVP Injecting Service Dependency

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

问题描述

我有一个ASP.NET页面实现我的视图,并在页面构件中创建演示者。 Phil Haack的职位提供用作起点,而我只是从帖子中的例子来说明这个问题。

  public partial class _Default:System.Web.UI.Page ,IPostEditView {

PostEditController controller;
public _Default()
{
this.controller = new PostEditController(this,new BlogDataService());
}
}

什么是最好的方法来注入BlogDataService?我已经发现的示例使用了在page类中的属性,该属性用注入框架解析的属性标记。



但是,我更喜欢使用构造函数方法进行测试有没有人有输入或者可能链接到上述的良好实现。



我喜欢Ninject,但是只要流畅,StructureMap或Windsor就会很好。



感谢任何反馈。

解决方案

如果您使用 Microsoft ServiceLocator ,您可以应用服务定位器设计模式,并询问容器的服务。



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

  public部分类_Default:System.Web.UI.Page,IPostEditView {

PostEditController controller;
public _Default()
{
var service = ServiceLocator.Current.GetInstance< IBlogDataService>();
this.controller = new PostEditController(this,service);
}
}

ServiceLocator具有Castle Windsor和StructureMap的实现。不确定Ninject,但是为新的IoC创建一个ServiceLocator适配器是微不足道的。


I have an ASP.NET page that implements my view and creates the presenter in the page constuctor. Phil Haack's post providing was used as the starting point, and I'll just the examples from the post to illustrate the question.

public partial class _Default : System.Web.UI.Page, IPostEditView {

    PostEditController controller;
    public _Default()
    {
         this.controller = new PostEditController(this, new BlogDataService());
    }
}

What is the best approach to inject the instance of the BlogDataService? The examples I have found use properties in the Page class for the dependency marked with an attribute which the injection framework resolves.

However, I prefer using the constructor approach for testing purposes.

Does anyone have input or perhaps links to good implementations of the above. I would prefer Ninject, but StructureMap or Windsor would be fine as long as its fluent.

Thanks for any feedback.

解决方案

If you use the Microsoft ServiceLocator, you can apply the service locator design pattern and ask the container for the service.

In your case it would look something like this:

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);
    }
}

ServiceLocator has implementations for Castle Windsor and StructureMap. Not sure about Ninject, but it's trivial to create a ServiceLocator adapter for a new IoC.

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

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