Calling DI Container directly in method code (MVC Actions)
- by fearofawhackplanet
I'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?