What does an IoC container do, and when is it worth using?
It creates objects, works out their dependencies and injects them for you, often also controlling their lifetime. It saves manual wiring in large applications, but is unnecessary in small ones.
Explain it simply
In a big college fest, a coordinator assigns volunteers to stalls and gives each one the equipment it needs. You do not walk round fetching mikes and tables yourself. An IoC container is that coordinator: you describe what each class needs, and it builds the right objects in the right order.
Frameworks such as Spring (Java), .NET's built-in container and NestJS (JavaScript) work this way. Their configuration styles differ, but the idea is the same.
Example
Manual wiring (small app):
db = new Database(url)
repo = new OrderRepository(db)
mailer = new Mailer(smtpHost)
service = new OrderService(repo, mailer)
Container (large app):
register Database, OrderRepository, Mailer, OrderService
container.get(OrderService) -> builds db, repo, mailer first, then serviceContainer benefits: one place for wiring, lifetimes (one shared instance versus a new one per request), and easy swapping per environment. Costs: wiring errors can appear at startup or runtime, and it adds a framework to learn. For a handful of classes, manual wiring in main is clearer.
What to say in the interview
"An IoC container builds and wires objects according to declared dependencies and manages their lifetimes. It pays off in larger applications with many services. In a small project, plain constructor injection with manual wiring is simpler and easier to follow."
Common mistakes
- Using a container for a ten-class project and hiding simple wiring behind annotations.