开发者

Calling DI Container directly in method code (MVC Actions)

I开发者_StackOverflow社区'm playing with DI (using Unity). I've learned how to do Constructor and Property injection. I have a static container exposed through a property in my Global.asax file (MvcApplication class).

I have a need for a number of different objects in my Controller. It doesn't seem right to inject these throught the constructor, partly because of the high quantity of them, and partly because they are only needed in some Actions methods.

The question is, is there anything wrong with just calling my container directly from within the Action methods?

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.
}

This seems the simplest and most efficient way of doing things, but I've never seen an example used in this way.

Is there anything wrong with this? Am I missing the concept in some way?


Yes, there is something wrong with using a static Service Locator because it's an anti-pattern.

Constructor Injection is your best option. If the constructor grows too large, it's a sign that the Controller violates the Single Responsibility Principle and that you should refactor to aggregate services.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜