Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is using IoC appropriate?

I understand what IoC containers are and have been reading up on Structure Map. The technology seems easy enough to use. My question is, what is the appropriate level of granularity for using an IoC container?

I see the following possible levels of application for IoC:

  1. Break every dependency between all objects - certainly overkill.
  2. Break dependencies between all major objects such as domain objects, support classes, and components within subsystems.
  3. Use IoC in conjunction with a Facade to wrap a subsystem (such as logging) with a public interface and then break the dependency on that interface.

I know the answer to this question is "it depends", but from your experience, what does then answer depend on? Is project size a factor?

Furthermore, where doesn't IoC make sense to use?

like image 245
Ryan Michela Avatar asked Jun 10 '09 17:06

Ryan Michela


2 Answers

The idea isn't to break dependencies between domain objects, it's to shield your domain from the outside world. Your domain objects should be about whatever business problem you are solving and not about databases, logging, caching, http contexts, rest services etc...

This article talks about moving responsibilities out of your objects and into the IoC container.

http://www.agileatwork.com/captcha-and-inversion-of-control/

like image 118
Mike Valenty Avatar answered Sep 18 '22 11:09

Mike Valenty


I think it makes sense to use it when you know you will be writing a lot of unit tests as it makes the construction of those tests easier. Also, it allows you (via external configuration) to change the behavior of objects during runtime.

It doesn't make sense to use IoC on smaller projects or projects that don't need massive decoupling.

like image 20
Peter D Avatar answered Sep 19 '22 11:09

Peter D