views:

27

answers:

1

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?

+2  A: 

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.

Mark Seemann
Thanks Mark, they are very good blog posts. Maybe tou are right that my Controller violates SRP. It seems an easy trap to fall into in MVC... everything to do with Orders should go into the OrdersController, right? Well, I guess maybe not after all. But how do you know when you have sufficient granularity in defining a responsibility? The responsibility of my Controller is to forward data between the Respository and the Views. I guess you could argue that is a Single Responsibility. But it still requires half a dozen helper objects, depending on which bit of the view is changing.
fearofawhackplanet
That happens a lot with Controllers, and there's not necessarily anything wrong with that. My point is just that we can often aggregate those many atomic dependencies into some higher-order abstractions. This gives us more layers, but each layer becomes less complex in isolation.
Mark Seemann