Tutorials About

Dependency Injection Containers

Last updated: 2014-05-25

If all components in your system have their dependencies injected, somewhere in the system some class or factory must know what to inject into all these components. This what a dependency container does. The reason it is called a container and not a factory is that the container often takes on more responsibility than just instantiating objects and injecting dependencies.

When configuring a dependency injection container you define what components it should be able to instantiate, and what dependencies to inject into each component. In addition you can normally configure the instantiation mode for each component. For instance, should a new instance be created every time? Or should the same component instance be reused (singleton) everywhere it is injected?

If some components are configured as singletons some containers are able to call methods on the singleton when the container is shut down. That way the singleton can release any resources it may hold, like database or network connections. This is often referred to as "instance life cycle management". This means that the container is capable of managing the component throughout the various stages of the components life cycle. For instance, instantiation, configuration and disposal.

Life cycle management is one of the responsibilities dependency containers assume in addition to instantiation and injection. The fact that the container sometimes keep a reference to the components after instantiation is the reason it is called a "container", and not a factory. Dependency injection containers usually only keep a reference to objects it needs to manage life cycles for, or that are reused for future injections, like singletons or flyweights. When configured to create new instances of some components for each call to the container, the container usually just forgets about the created object. Otherwise the garbage collector would have a hard time collecting all these objects when no longer used.

There are several dependency injection containers available. For Java you have our own Butterfly Container, as well as Spring, Pico Container, Guice, and others.

Connect with me: Newsletter - Get all my free tips!

Close TOC
This website uses cookies to improve the user experience and gather statistics. Our advertisers use cookies too (3rd party cookies), to provide more relevant ads. Continued use of this website implies that you accept the use of cookies on this website. We do not share our cookies with our advertisers, and our advertisers do not share cookies with us.