直接在方法代码中调用DI容器(MVC操作)

时间:2010-06-15 10:38:22

标签: design-patterns dependency-injection ioc-container

我正在玩DI(使用Unity)。我已经学会了如何进行构造函数和属性注入。我有一个静态容器通过我的Global.asax文件(MvcApplication类)中的属性公开。

我的Controller中需要许多不同的对象。通过构造函数注入这些似乎是不对的,部分原因在于它们的数量很大,部分原因是它们仅在某些Actions方法中需要。

问题是,直接从Action方法中调用我的容器有什么问题吗?

public ActionResult Foo()
{
    IBar bar = (Bar)MvcApplication.Container.Resolve(IBar);
    // ... Bar uses a default constructor, I'm not actually doing any
    // injection here, I'm just telling my conatiner to give me Bar
    // when I ask for IBar so I can hide the existence of the concrete
    // Bar from my Controller.
}

这似乎是最简单,最有效的做事方式,但我从未见过以这种方式使用过的例子。

这有什么问题吗?我是否以某种方式错过了这个概念?

1 个答案:

答案 0 :(得分:3)

是的,使用静态服务定位器 是错误的,因为it's an anti-pattern

构造函数注入是您的最佳选择。如果构造函数变得过大,则表示Controller违反了Single Responsibility Principle并且您应该refactor to aggregate services