Skip to main content

What is a dependency container?

A dependency container (Dependency Injection Container, IoC Container) is a dedicated mechanism that creates, stores, and wires objects together according to their dependencies.

It implements the Inversion of Control (IoC) principle: instead of the code creating its own dependencies, the container does it instead.


In simpler terms:

A dependency container is an "object factory" that knows which classes depend on what and in what order to create them, so the whole system starts working.


How it works

  1. You describe the relationships between interfaces and implementations:
java
bind(Database.class).to(MySQLDatabase.class);
  1. When an object is needed, the container:
  • finds its dependencies,
  • creates the needed instances (in the right order),
  • "injects" them wherever they are needed.
  1. The container manages the lifecycle of objects: it decides where a single shared instance is needed (singleton), and where a new one is needed on every request (prototype).

Example (Java, with Guice)

java
public class AppModule extends AbstractModule { @Override protected void configure() { bind(Database.class).to(MySQLDatabase.class); } } public class UserService { private final Database db; @Inject public UserService(Database db) { this.db = db; } } // somewhere in the code: Injector injector = Guice.createInjector(new AppModule()); UserService service = injector.getInstance(UserService.class);

The container itself:

  • creates MySQLDatabase,
  • plugs it into UserService,
  • hands back a ready-made object.

What a dependency container does

TaskWhat it does
Creating objectsAutomatically creates instances of the needed classes.
Resolving dependenciesFinds which dependencies a class needs and plugs them in.
Lifecycle managementControls when an object is created, reused, or destroyed.
ConfigurationLets you configure which implementations to use (for example, MySQLDatabase or PostgresDatabase).
Dependency injectionInjects dependencies into fields, constructors, or setters.

Examples of containers in different languages:

LanguageContainers
JavaSpring IoC, Guice, CDI
.NETMicrosoft.Extensions.DependencyInjection, Autofac, Ninject
Pythondependency-injector, FastAPI Depends
JavaScript/TypeScriptInversifyJS, NestJS
PHPSymfony DI Container, Laravel Container

Why it is needed

Removes tight coupling between classes Makes testing easier - dependencies can be swapped Lets you configure behavior without changing code Makes the architecture scalable Centralizes dependency management


Conclusion:

A dependency container is the heart of a system built with Dependency Injection. It manages the creation, wiring, and lifetime of objects, letting the developer focus on the logic rather than on who creates the dependencies and how.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.