Service Locator vs Dependency Injection
Two common implementations of IoC are the
service locator pattern and
dependency injection. A service locator provides a central repository for objects
to request dependencies. Dependency injection takes the inversion principle even
further by allowing a container to inject dependencies
directly into components
through constructor arguments or setter methods.
Constructor Injection vs Setter Injection
Constructor injection requires a component to declare a constructor with
arguments for every dependency. This allows any
initialization logic to run
in the constructor, but components with multiple dependencies may have
unwieldy constructor declarations. Setter injection
requires a component
to declare setter methods for every dependency. Setter injection is more flexible,
but any initialization logic must take place after all the dependencies have been
injected.
In either case, a container is required to manage the relationship
between components and their dependencies.