【发布时间】:2010-06-15 10:38:21
【问题描述】:
我正在玩 DI(使用 Unity)。我已经学会了如何进行构造函数和属性注入。我有一个通过 Global.asax 文件(MvcApplication 类)中的属性公开的静态容器。
我的控制器中需要许多不同的对象。通过构造函数注入这些似乎不太合适,部分原因是它们的数量很大,部分原因是它们仅在某些 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.
}
这似乎是最简单和最有效的做事方式,但我从未见过以这种方式使用的示例。
这有什么问题吗?我在某种程度上错过了这个概念吗?
【问题讨论】:
标签: design-patterns dependency-injection ioc-container