Dependency injection interview questions and answers
Dependency injection interview questions test whether you can explain why a class should receive its collaborators instead of creating them, where the wiring belongs (one composition root), and what a container's lifetimes (singleton, scoped, transient) mean for shared state. Senior rounds probe the failure modes: a singleton holding a per-request object, a service locator hiding dependencies, circular references and constructors with twelve parameters. Show the trade-off, not just the definition.
By Evin JohnPublished 9 min read
Where dependency injection questions come up
Almost every backend framework is built on an injector, so DI questions appear wherever those frameworks are used: Spring and Spring Boot in Java and Kotlin, ASP.NET Core in C#, Angular and NestJS in TypeScript, FastAPI and some larger Python codebases. Junior candidates are asked what it is and why it helps testing. Mid-level candidates are asked about lifetimes and registration. Senior candidates get a design to critique, usually one where the wiring has leaked into business code or a shared object holds request data. The underlying principle has its own treatment in SOLID principles interview questions; this page stays on the mechanics and the bugs.
- Define it in one breathA class gets what it needs from outside, usually through its constructor, instead of calling
newon concrete collaborators or reaching for globals. - Explain the payoffSwappable implementations, tests with fakes, one place to change configuration, and dependencies you can read from a constructor signature.
- Know your framework's containerHow registration works, what each lifetime means, how it picks between two implementations, and what it does on a cycle.
- Spot the misuseCaptive dependencies, service locator calls inside methods, static singletons, and classes that take too many dependencies.
Dependency injection fundamentals
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is dependency injection? | Core idea | Giving an object its dependencies from outside rather than having it construct or look them up. The object states what it needs; something else decides which implementation it gets. |
| IoC, DIP and DI: how are they different? | Vocabulary | Inversion of control is the broad idea that a framework calls your code. The dependency inversion principle is a design rule about depending on abstractions. DI is a technique for supplying dependencies, which often helps you follow DIP but is not the same thing. |
| Constructor, setter or method injection? | Injection styles | Constructor injection for required dependencies, because the object is never half-built and fields can be final or readonly. Setter injection for genuinely optional ones. Method injection when a dependency is needed for one call only, such as a per-request context. |
| Why is field injection discouraged in Spring? | Framework detail | Fields set by reflection hide dependencies from the constructor, cannot be final, and make plain unit tests awkward without the container. Constructor injection makes the same needs explicit. |
| How does DI make testing easier? | Testability | A test passes a fake or stub through the constructor and checks behavior without a database, network or clock. Without DI, tests patch globals or need the whole application running. |
| Do you need a container to do DI? | Pure DI | No. Passing collaborators into constructors by hand in main is DI. A container automates the wiring and lifetimes, which pays off as the graph grows. |
| What is the composition root? | Where wiring lives | The single place near the entry point where the object graph is assembled, such as the startup file or main. Business classes never call the container themselves. |
What does new in a service class tell you? | Code smell | Creating a concrete dependency inside a class (a repository, an HTTP client) couples them. Creating value objects or data structures with new is fine; the concern is collaborators with behavior or I/O. |
| What should you inject: interfaces or concrete classes? | Abstractions | Inject an abstraction where there are, or will realistically be, several implementations or a test double is needed. Wrapping every class in a one-implementation interface adds files without adding options. |
| Is a static utility class compatible with DI? | Globals | Pure functions without state or I/O are fine as statics. Statics that read the clock, the environment or a database hide a dependency and should become injected services. |
Containers and lifetimes
Lifetime questions are where most candidates lose marks. The names differ by framework (Spring calls the default scope singleton and adds prototype, request and session; ASP.NET Core uses singleton, scoped and transient), but the model is the same: how long one instance lives and who shares it. The sketch below is a toy container, written to show the rules rather than to be used.
class Container {
#regs = new Map();
#singletons = new Map();
register(name, lifetime, deps, make) {
this.#regs.set(name, { lifetime, deps, make });
return this;
}
scope() {
const s = { cache: new Map() };
s.resolve = (name) => this.#resolve(name, s, null);
return s;
}
#resolve(name, scope, parentLifetime) {
const reg = this.#regs.get(name);
if (!reg) throw new Error(`No registration for ${name}`);
if (parentLifetime === "singleton" && reg.lifetime === "scoped")
throw new Error(`Captive dependency: singleton depends on scoped ${name}`);
// anything built for a singleton lives as long as the singleton does
const owner = parentLifetime === "singleton" ? "singleton" : reg.lifetime;
const build = () =>
reg.make(...reg.deps.map((d) => this.#resolve(d, scope, owner)));
if (reg.lifetime === "transient") return build();
const cache = reg.lifetime === "singleton" ? this.#singletons : scope.cache;
if (!cache.has(name)) cache.set(name, build());
return cache.get(name);
}
}
let ids = 0;
const c = new Container()
.register("clock", "singleton", [], () => ({ now: () => new Date() }))
.register("db", "scoped", [], () => ({ id: ++ids }))
.register("orders", "transient", ["db", "clock"], (db, clock) => ({ db, clock }));
const req1 = c.scope();
const req2 = c.scope();
const a = req1.resolve("orders");
const b = req1.resolve("orders");
const d = req2.resolve("orders");
console.log(a === b, a.db === b.db, a.db === d.db, a.clock === d.clock);
// false true false true
c.register("repo", "transient", ["db"], (db) => ({ db }));
c.register("cache", "singleton", ["repo"], (repo) => ({ repo }));
try {
req1.resolve("cache");
} catch (e) {
console.log(e.message);
}
// Captive dependency: singleton depends on scoped db- What do singleton, scoped and transient mean? One instance for the application's life, one per scope (usually one web request), and a new instance on every resolve. The printout above shows it: two resolves of a transient in one request are different objects that share the same scoped
db. - What is a captive dependency? A longer-lived object holding a shorter-lived one, such as a singleton cache keeping the first request's database context forever. The symptoms are stale data, data from one user leaking into another, or a disposed object used later.
- How do frameworks catch it? Some validate the graph at startup; ASP.NET Core can check scopes when the provider is built, and it is commonly switched on in development. Otherwise it surfaces as a runtime bug, which is why reviewers look for it.
- How should a singleton use a scoped service legitimately? Create a scope when it needs one, for example a background worker that opens a scope per message through a scope factory, resolves the scoped service inside it and disposes it afterwards.
- What must be true of a singleton? It must be safe to call from many threads at once, so it should be stateless or guard its state. A singleton with a mutable field written per request is a race condition.
- Who disposes what? The container disposes what it created, at the end of the scope or application. Objects you constructed yourself and handed to it are often yours to clean up; check how your framework treats instances registered directly.
- What is the Spring prototype-in-singleton problem? A prototype bean injected into a singleton is created once, at injection time, so it behaves like a singleton. Ask the container for a new one each time with an object provider or lookup method instead.
Intermediate: registration and resolution
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Two classes implement the same interface. How does the container choose? | Ambiguity | By name or qualifier (@Qualifier, @Primary in Spring; keyed registrations in recent .NET; injection tokens in Angular), or by injecting all of them as a collection when the code should use every one. |
| How do you inject a value only known at runtime, such as a tenant ID? | Runtime data | Do not register it as a service. Inject a factory that takes the value as a parameter, or pass it as a method argument. Containers wire structure; data flows through calls. |
| What is the difference between registering a type and an instance? | Registration | A type registration lets the container build and manage it with its lifetime. An instance registration hands over an object you built, which is always effectively a singleton. |
| How would you add logging or retries to a service without editing it? | Decorators | Register a decorator that implements the same interface and wraps the real one. Some containers support decoration directly; otherwise wire it in the composition root. |
| How does Angular's injector differ from a server container? | Hierarchical DI | Injectors form a tree. A service provided in root is shared app-wide; one provided in a component gets a new instance for that component subtree. Newer Angular code often uses the inject() function instead of constructor parameters. |
How does FastAPI's Depends relate to DI? | Python | It resolves function parameters per request, including generator dependencies that clean up after the response. It is DI at the function level rather than a global object graph. |
| What does auto-wiring by convention cost you? | Magic | Scanning assemblies or packages saves registration lines but makes it harder to see what is in the graph and why a type was picked. Large teams often keep scanning narrow. |
| How do you configure options or settings through DI? | Configuration | Bind a typed settings object from configuration and inject it, instead of reading environment variables deep inside services. It keeps configuration testable and validated at startup. |
Senior and design scenario questions
- Why is service locator called an anti-pattern? A class that calls
container.get(X)inside its methods hides its dependencies: you cannot see them in the constructor, tests must configure a container, and a missing registration fails at runtime deep in a call. It is acceptable at the composition root or in framework glue, not in business logic. - Two services depend on each other. What do you do? Treat the cycle as a design signal. Extract the shared part into a third service, reverse one dependency with an event or callback, or merge them if they are really one thing. Lazy injection that hides the cycle is a last resort, and some frameworks now refuse cycles by default.
- A constructor takes eleven dependencies. What does it tell you? The class has too many jobs. Group related collaborators behind a facade only if they form a real concept; usually the fix is to split the class, which shrinks each constructor naturally.
- When would you not use a container? Small tools, libraries and scripts, where hand wiring in
mainis shorter and clearer. Libraries in particular should accept dependencies through constructors and leave the container choice to the application. - How do you test that the wiring itself is right? A startup test that builds the container and resolves every root type, plus framework scope validation where available, catches missing registrations and captive dependencies before deploy.
- What is the difference between DI and the strategy pattern? Strategy is a design where behavior varies by a swappable object; DI is how that object gets supplied. They often appear together but answer different questions.
- A legacy codebase news up everything. How do you introduce DI safely? Start at the edges: add constructor parameters with defaults that build today's concrete classes, cover the class with tests using fakes, then move the construction to a composition root one module at a time.
- Where does DI show up in test frameworks? Cucumber-JVM uses a DI container to share one state object between step definition classes in a scenario, which is a common question on Cucumber interview questions. PHP frameworks vary: CodeIgniter 4's Services class is closer to a central factory you call, covered in CodeIgniter interview questions.
Fictional example
- Interviewer
- A reporting service is registered as a singleton and caches results. Customers occasionally see someone else's numbers. The cache code looks correct. What would you look for?
- Candidate
- I would look at what the singleton was constructed with. If it takes the request's user context or a database context that is scoped per request, it captured the first one it saw and keeps using it, so the cache key or the query is built from the wrong tenant. I would confirm by logging the context ID inside the singleton across two requests. The fix is to keep the singleton stateless about the request: pass the tenant into the method as an argument, or have it create a scope per call. Then I would turn on scope validation at startup so the container rejects the registration next time, and add a test that resolves the service in two scopes and checks they do not share the context.
A one-week practice plan
- Days 1 and 2: take a small app in your interview language and wire it by hand in
mainwith no container. Write one test that swaps a fake in. - Day 3: move the wiring into your framework's container. Register one service of each lifetime and print object identities across two requests.
- Day 4: create a captive dependency on purpose and see whether your framework catches it at startup or only at runtime.
- Day 5: write a decorator for logging and a factory for a runtime value, and say why each is not a plain registration.
- Days 6 and 7: practice explaining service locator, cycles and over-injection out loud in under a minute each, with one example from your own work.
For the framework layer, Spring Boot interview questions covers beans, scopes and auto-configuration, and .NET interview questions covers the ASP.NET Core host and its built-in container.
DI answers fall apart when they stay abstract, and it is easy to drift into definitions without noticing. Natively, an AI interview assistant for Mac and Windows, transcribes your mock design round on your computer, so you can check afterwards whether you ever named a lifetime or a concrete failure. In practice it can read a code snippet from a screenshot and suggest what to point out, help with coding questions, and, with Pro or the free trial, use the résumé and job description you add. The transcript and notes are kept for review.
Questions people ask
What dependency injection questions are asked in interviews?
What DI is and how it differs from IoC and the dependency inversion principle, constructor versus setter injection, the composition root, singleton, scoped and transient lifetimes, captive dependencies, service locator, circular dependencies and testing.
What is a captive dependency?
A longer-lived object, usually a singleton, that holds a shorter-lived one such as a per-request database context. The short-lived object outlives its scope, causing stale or leaked data.
Why is constructor injection preferred?
Required dependencies are visible in one place, the object can never exist half-built, fields can be immutable, and tests can pass fakes without a container.
Is service locator an anti-pattern?
Inside business classes, usually yes, because it hides dependencies and moves failures to run time. At the composition root or in framework glue code it is acceptable.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
