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
- You describe the relationships between interfaces and implementations:
bind(Database.class).to(MySQLDatabase.class);- When an object is needed, the container:
- finds its dependencies,
- creates the needed instances (in the right order),
- "injects" them wherever they are needed.
- 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)
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
| Task | What it does |
|---|---|
| Creating objects | Automatically creates instances of the needed classes. |
| Resolving dependencies | Finds which dependencies a class needs and plugs them in. |
| Lifecycle management | Controls when an object is created, reused, or destroyed. |
| Configuration | Lets you configure which implementations to use (for example, MySQLDatabase or PostgresDatabase). |
| Dependency injection | Injects dependencies into fields, constructors, or setters. |
Examples of containers in different languages:
| Language | Containers |
|---|---|
| Java | Spring IoC, Guice, CDI |
| .NET | Microsoft.Extensions.DependencyInjection, Autofac, Ninject |
| Python | dependency-injector, FastAPI Depends |
| JavaScript/TypeScript | InversifyJS, NestJS |
| PHP | Symfony 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 readyA concise answer to help you respond confidently on this topic during an interview.