📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the composition root, and why should only the composition root resolve services from the container?

Beginner Theory Beginner aspnetcore composition-root dependency-injection service-locator testability

🎯 Key points

  • Composition root = the one place the object graph is composed (Program.cs plus AddXxx() extension methods)
  • Only it references concrete implementations and the container
  • Business code takes dependencies through constructors, never IServiceProvider
  • Resolving elsewhere is the service locator anti-pattern: hidden dependencies, runtime failures
  • Constructor-only dependencies make classes testable without a container
  • Framework resolution (middleware Invoke, [FromServices], endpoint parameters) is infrastructure, so acceptable

⏱ 30-second answer

The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.

Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.

🔍 What the interviewer is checking

Checks the candidate can say where composition happens and why business code must not reach for the container.

Green flags

  • Names Program.cs and AddXxx() extension methods
  • Links resolving elsewhere to the service locator anti-pattern
  • Mentions testability and hidden dependencies

Red flags

  • Injects IServiceProvider into domain services as a matter of habit
  • Thinks the composition root is a class you inject

↩ Usually asked after

More in DI Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me