Assuming I'm using an IoC container, why exactly must my types have their dependencies injected? Why can't every type just assume that the container exists and just retrieve the dependencies it needs for itself? What are the disadvantages to this latter approach?
I'm aware of property injection but I don't want that suggested as an answer even though it does save on having long parameter list constructors in more complex types. And this doesn't save on the code you ultimately need to type/maintain. Oh, and I'd prefer to have the dependencies readonly/final (personal preference).
So here's a typical example of constructor injection in C#:
public class Calculator
{
private readonly IAdder _adder;
private readonly ISubtractor _subtractor;
private readonly IMultiplier _multiplier;
private readonly IDivider _divider;
public Calculator(IAdder adder, ISubtractor subtractor,
IMultiplier multiplier, IDivider divider)
{
_adder = adder;
_subtractor = subtractor;
_multiplier = multiplier;
_divider = divider;
}
}
And here's what I'd rather do:
public class Calculator
{
private readonly IAdder _adder;
private readonly ISubtractor _subtractor;
private readonly IMultiplier _multiplier;
private readonly IDivider _divider;
public Calculator()
{
_adder = Container.Get<IAdder>();
_subtractor = Container.Get<ISubtractor>();
_multiplier = Container.Get<IMultiplier>();
_divider = Container.Get<IDivider>();
}
}
I'd like to maintain a list of pros and cons as the answers come in:
PROS
- Clean constructors as types need not "pollute" their constructors with dependencies. It's not a big problem here because Calculator doesn't have anything in its constructor other than dependencies but imagine it did. E.g.
public Calculator(Mode mode, bool UseDigitGrouping)
. - Client code doesn't break when a dependency's dependencies change.
- Less code to maintain.
CONS:
- Harder to change IoC container in the future.
- It's not immediately clear what a type's dependencies are.