Constructor Injected Dependency vs. Setter Injected Dependeny

Just a thought: I always felt more comfortable with CID than with SID, but that was really just a feeling. While I was reading some code, I realized that with CID there is no chance that a dependency will show up in the interface, because interfaces don't have constructors. So the dependencies of a service are much better hidden from the clients of the service.

Of course one could separate the service interface and dependency interface and I would do just that if I couldn't go with CID.

Which leads to another interesting topic: In what situations is CID not working?

Off the top of my head I can thing of the following situations:

  • Legacy Code: Obvious! You would be lucky if that stuff used Dependency Injection at all, so do not get greedy!
  • Cyclic Dependencies: That should be avoided anyway, right?
  • Optional Dependencies: Not really. I would rather inject a default implementation (e.g. something like a Null Object).

Right now I can't think up any more scenarios.

del.icio.us Tags: , ,

1 comment:

Andrei Pamula said...

I think these are 2 orthogonal aspects: an interface describes the contract of a service: what it does. The constructor/class/object describe how the service is fulfilled.

Regarding CID in Legacy code: On a project I used an IoC container for a component. All the external (non-ioc) components used
a very thin (sorry, static) ServiceLocator wrapper around the IoC container.

I can very warmly recomend "Working effectively with Legacy Code" from Michael Feathers.

Some people say that CID does not suit very well when you want to rewire objects during runtime. In CID I would implement this by injecting a getter to the service, ("the path to the target is the target").


whos online

Ralf"s shared items