Dependency injection (DI) means an object receives the objects it works with (its dependencies) from outside, usually through its constructor, instead of creating them or fetching them from a global. Creation and wiring move to one place at startup, the composition root, so business classes only use their collaborators. The payoff is that every dependency is visible in a signature, and the same class can be wired with real services in production and with fakes in a test, without being edited. Frameworks such as Spring, Angular and NestJS are built around it, but DI itself needs no framework: passing an argument is enough.
Think of it like
A film set's prop department
An actor does not build the sword, the phone or the coffee cup they use in a scene. The prop department hands them over before the take, and the actor just uses them. For a rehearsal the department hands over a wooden sword and an empty cup; the actor plays the scene exactly the same way. The actor is the service, the props are the dependencies, the prop department is the composition root, and the rehearsal props are the fakes a test passes in.
The problem
A shop's CheckoutService charges the customer's card, emails a receipt and stamps it with the time. The quickest way to write it is to let the service build what it needs: new StripeGateway(), new SmtpMailer() and a direct read of the system clock. This is the Before version in the visualizer above.
class CheckoutService {
private gateway = new StripeGateway();
private mailer = new SmtpMailer();
checkout(amt: number, to: string): string {
const time = new Date().toTimeString().slice(0, 5);
const id = this.gateway.charge(amt); // real money
const msg = `${id} at ${time}`;
this.mailer.send(to, msg); // real email
return msg;
}
}
// main
const svc = new CheckoutService();
svc.checkout(499, "asha@ok"); // "ch_1 at 14:05", for exampleIt works in production. The cost shows up as soon as anyone wants to use the class any other way:
- Hidden dependencies. The constructor takes nothing, yet the class needs Stripe, an SMTP server and the clock. You find out by reading its body, or when it fails on a machine without network access.
- Untestable without side effects. A unit test can only call
new CheckoutService(), so it charges a real card and sends a real email. In the visualizer's Test scenario,stripe.chargesandsmtp.sentboth reach 1 during the test. - Nondeterministic results. The receipt contains the current time, so the expected value changes every minute. The test cannot state what the right answer is.
- Every swap edits the service. Moving to another payment provider or mail service means opening
CheckoutService, a class whose job is checkout, not choosing vendors. - Locked-in lifetimes. Each service creates its own gateway, so ten services mean ten connection setups; sharing one requires a global, which brings back hidden dependencies (see Singleton).
The pattern
Intent: separate using an object from creating it. A class declares the dependencies it needs, preferably as interfaces in its constructor, and something outside the class (the composition root, a test, or a DI container) creates those dependencies and passes them in. The name comes from Martin Fowler's 2004 article on inversion-of-control containers.
- Client or service (
CheckoutService) - The class that needs collaborators. It stores what it is given and calls it. It never names a concrete dependency class.
- Dependency (
Gateway,Mailer,Clock) - What the client needs, usually typed as an interface so any implementation fits. Following DIP (SOLID Principles), the client's side owns these interfaces.
- Implementation (
StripeGateway,FakeGateway, ...) - Concrete classes behind each interface: real ones for production, fakes for tests.
- Injector, or composition root (
main, the test) - The code that creates the implementations and passes them to the client. In a small program it is
main; in a framework it is a container configured at startup; in a test it is the test itself.
The client has an association to each interface and nothing else, and each implementation implements one interface. Creation flows in the other direction: the root builds the leaves first (objects that need nothing), then the objects that need them, and passes each one down. Only the root knows the concrete classes, so only the root changes when the choice changes.
What the visualizer shows
The visualizer holds two scenarios with the same CheckoutService. Choose Production or Test in the toolbar, then Before or With DI, and press Play or step with the arrow keys. The engine really runs the classes in the code panel; the highlighted line and the caption follow each step. Choosing a scenario starts it on its With DI version.
- Class diagram: Before,
CheckoutServicehas filled diamonds (composition) toStripeGatewayandSmtpMailer: it creates and owns them. With DI, its three arrows point at the interfacesGateway,MailerandClock, and the implementations hang below them. In Test the bottom row isFakeGateway,FakeMailerandFixedClock; the top two rows do not change. - Objects at runtime: in Production With DI the client (
main) createsclock,stripeandsmtpfirst, thensvc, whose fieldsgateway = stripe,mailer = smtpandclock = clockpoint at objects it did not create. In Before,svcitself createsstripeandsmtpwhile its constructor runs. - Sequence of calls: during
checkout,svccallsnow(),charge(499)andsend(...)on whatever it holds. In Test the same three calls reach the fakes, and the field values show what they recorded:fakePay.charges = [499]andfakeMail.sent = ["qa@test"].
The production clock in the visualizer is real: the time on the receipt is your local time when the page loaded. Run Test With DI at any hour and the receipt is always fake_1 at 09:00. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Read the constructor
In Production With DI, the first step points at
CheckoutService's constructor:gateway: Gateway,mailer: Mailer,clock: Clock. Everything the class needs is in its signature, typed as interfaces. - 2
The root creates the leaves
mainis the composition root. It createsclock(aSystemClock),stripe(aStripeGateway,charges = 0) andsmtp(anSmtpMailer,sent = 0). These need nothing, so they come first. - 3
Inject them
new CheckoutService(stripe, smtp, clock)createssvc. Its constructor only stores the three references. The object graph is now complete, andmainis the only code that named a concrete class. - 4
Use them
The client calls
svc.checkout(499, "asha@ok").svccallsclock.now()(the real time),stripe.charge(499)(chargesbecomes 1, returns"ch_1") andsmtp.send(...), then returns the receipt. Same behavior as Before. - 5
Switch to Test
Choose Test. The test is a second composition root. It creates
fakePay(aFakeGateway),fakeMail(aFakeMailer) andclock, aFixedClockset to"09:00", and passes them to the very sameCheckoutServiceconstructor. - 6
Same calls, no side effects
svc.checkout(499, "qa@test")makes the same three calls.clock.now()returns"09:00",fakePay.charge(499)records[499]and returns"fake_1", andfakeMail.sendrecords["qa@test"]. No card is charged and no email leaves the process. - 7
Assert
The receipt is
"fake_1 at 09:00"on every run, so the test asserts it exactly, and checks the fakes: one charge of ₹499, one receipt to the right address.CheckoutServicewas not edited for any of this.
Before and after
Service builds its own
constructor()takes nothing; dependencies hide in the body- The class picks Stripe, SMTP and the system clock itself
- A test charges a real card and sends a real email
- The receipt depends on the current time, so it cannot be asserted
- Swapping a vendor edits the business class
With dependency injection
- The constructor lists every dependency, typed as an interface
- The composition root picks the implementations, once
- A test passes fakes: nothing real happens
- A fixed clock makes the result deterministic
- Swapping a vendor changes one line in the root
Unit test of checkout(499, ...) | Before | With DI |
|---|---|---|
| Real card charges made by the test | 1 (stripe.charges = 1) | 0 (fakePay.charges = [499], only recorded) |
| Real emails sent by the test | 1 (smtp.sent = 1) | 0 (fakeMail.sent = ["qa@test"], only recorded) |
| Receipt returned | ch_1 at the current time | fake_1 at 09:00, every run |
| Can the expected value be written down? | No | Yes |
Edits to CheckoutService to make it testable | Needed (flags, a second constructor or a global) | 0: the same class runs in both scenarios |
DI, DIP, IoC and service locator
Four terms that are often mixed up. The SOLID Principles lesson separates the first three; here they are side by side with the main alternative to DI.
| Term | What it is | In the checkout example |
|---|---|---|
| Dependency inversion principle (DIP) | A design rule: policy and details both depend on an abstraction that the policy owns | Gateway is shaped by what CheckoutService needs, and StripeGateway implements it |
| Dependency injection (DI) | A technique: an object receives its collaborators instead of creating or looking them up | main passes stripe, smtp and clock to the constructor |
| Inversion of control (IoC) | The broad idea that a framework calls your code (callbacks, template methods, event handlers, containers) | A container that builds CheckoutService for you is IoC applied to construction |
| Service locator | A registry the class asks for its dependencies: Locator.get(Gateway) | The class pulls its gateway from a global registry instead of being handed one |
DI without DIP is possible (injecting a concrete StripeGateway still makes the dependency visible, but a test cannot easily pass something else), and DIP without DI is possible (a factory hands out the interface). They are usually used together.
class CheckoutService {
checkout(amt: number, to: string): string {
const gateway = Locator.get<Gateway>("gateway");
const mailer = Locator.get<Mailer>("mailer");
// ...same body as before
}
}
// The constructor says nothing; a test must know which keys to register
// in a global registry, and reset it afterwards.
Locator.register("gateway", new FakeGateway());Variations
Injection styles
| Style | How | Use it for | Trade-off |
|---|---|---|---|
| Constructor injection | new CheckoutService(gateway, mailer, clock) | Required dependencies (the default) | The object is complete from birth and fields can be readonly/final. A long parameter list is visible, which is a feature: it exposes classes that do too much |
| Setter (property) injection | svc.setLogger(logger) after construction | Optional dependencies with a sensible default, or breaking a construction cycle | The object exists in a half-wired state; forgetting the setter fails late, at the first call |
| Method (parameter) injection | report.render(clock) | A dependency that varies per call, or that only one method needs | Every caller must supply it; fine for a context object, noisy for something used everywhere |
| Field injection (framework) | @Autowired private Gateway gateway; | Avoid in new code | Needs reflection and a container; new in a test leaves the field null; dependencies are hidden again |
class ReportService {
private logger: Logger = new NullLogger(); // optional: safe default
setLogger(logger: Logger): void { // setter injection
this.logger = logger;
}
render(rows: Row[], clock: Clock): string { // method injection
this.logger.info(`render at ${clock.now()}`);
return rows.map(formatRow).join("\n");
}
}The NullLogger default is the Null Object pattern: it keeps optional dependencies free of if (logger) checks. The Spring team, among others, recommends constructor injection for mandatory dependencies and setters only for optional ones.
The composition root
The composition root is the single place, as close to the program's entry point as possible, where the object graph is built: main, the app's startup file, or the container configuration. Rules that keep it useful: compose everything there and nowhere else; let no other class see the container or the root; and keep it free of business logic. Tests have their own small roots, one per test or fixture.
Lifetimes
| Lifetime | How many instances | Typical use | Pure DI equivalent |
|---|---|---|---|
| Singleton | One per container (application) | Stateless or thread-safe services, connection pools, configuration, HTTP clients | Create once in main and pass the same object everywhere |
| Scoped | One per scope, usually one per web request | A database session or unit of work, the current user, request-wide caches | Create at the start of each request and pass it to that request's objects |
| Transient | A new one every time it is injected | Cheap, short-lived objects with per-use state | Call new each time you build a consumer |
A container's singleton lifetime is not the Singleton pattern: there is one instance because the root created one, not because the class forbids a second, and nobody reaches it through a global.
Containers and pure DI
A DI container is a library that builds the graph for you: you register which implementation serves each abstraction and with what lifetime, and the container reads constructors and creates objects in the right order. Pure DI (Mark Seemann's term) means writing the composition root by hand with new, as in the visualizer. Pure DI is checked by the compiler and has no magic; a container saves typing in large graphs and manages scopes and disposal. Both are dependency injection; the classes being injected look the same either way.
@Configuration
class AppConfig {
@Bean Gateway gateway() { return new StripeGateway(); }
@Bean Mailer mailer() { return new SmtpMailer(); }
@Bean Clock clock() { return new SystemClock(); }
}
@Service
class CheckoutService {
private final Gateway gateway;
private final Mailer mailer;
private final Clock clock;
// One constructor: Spring injects it without @Autowired.
CheckoutService(Gateway gateway, Mailer mailer, Clock clock) {
this.gateway = gateway;
this.mailer = mailer;
this.clock = clock;
}
}Testing with fakes and mocks
Injection is what makes test doubles possible: the test is a composition root that passes stand-ins. Gerard Meszaros's xUnit Test Patterns named the kinds of double, and Martin Fowler's article "Mocks Aren't Stubs" made the distinction widely known:
| Double | What it does | In the checkout example |
|---|---|---|
| Dummy | Fills a parameter that the test never uses | Any Mailer passed to a test that only checks a validation error |
| Stub | Returns canned answers | FixedClock always says "09:00" |
| Fake | A working, lightweight implementation | FakeGateway keeps charges in a list instead of calling Stripe |
| Spy | Records how it was called, for the test to check afterwards | FakeMailer.sent lists the recipients |
| Mock | Pre-programmed with expectations and verifies them itself (usually with a library such as Mockito or jest.fn()) | expect(gateway.charge).toHaveBeenCalledWith(499) |
Prefer fakes and stubs that check results and state (the receipt, the recorded charges) over mocks that check exact calls: state-based tests survive refactoring, while a mock that insists on charge being called before now breaks when the order changes for a harmless reason. Mocks earn their place when the interaction is the behavior, such as "exactly one email is sent". Whatever you use, keep fakes honest: a fake that accepts every card hides the declined-card path, so add a declining fake for that test.
In real code
| Where | How DI shows up |
|---|---|
| Spring (Java) | Beans declared with @Component/@Service or @Bean methods; constructor injection, and a single constructor needs no @Autowired. Scopes include singleton (the default), prototype, and request and session in web apps |
| Guice and Dagger (Java, Android) | Both use the standard @Inject annotation. Guice binds in modules at runtime (bind(Gateway.class).to(StripeGateway.class)); Dagger generates the wiring code at compile time from @Module and @Component classes, and Hilt builds on Dagger for Android |
| ASP.NET Core (.NET) | Microsoft.Extensions.DependencyInjection: services.AddSingleton<IGateway, StripeGateway>(), AddScoped (one per HTTP request) and AddTransient; controllers receive services through their constructors |
| Angular | @Injectable({ providedIn: 'root' }) services and a hierarchy of injectors; components receive services through the constructor or the inject() function |
| NestJS (Node.js) | Providers registered in @Module({ providers: [...] }) are injected into constructors; scopes are default (singleton), request and transient. Tests swap providers with overrideProvider(...).useValue(fake) |
| Python | FastAPI's Depends(...) injects per-request dependencies into route functions, and pytest fixtures are injected into tests by parameter name |
| Time as a dependency | Java's java.time.Clock (Clock.fixed(...) in tests) and .NET's TimeProvider exist so that code can take the clock as an injected dependency, exactly like the visualizer's Clock |
When to use it, and when not to
Inject when the dependency
- Talks to the outside world: network, database, file system, email
- Is nondeterministic: the clock, random numbers, UUIDs
- Has more than one implementation, now or in tests
- Is expensive or shared, so its lifetime should be decided centrally
- Is configured per environment (sandbox gateway in staging)
Just create it when it is
- A value or data object (
Money,Address, a DTO) - A pure helper with no side effects (a formatter, a parser)
- Part of the standard library that will never be swapped (a list, a map)
- Created per call from method arguments (that is a factory's job)
- In a short script, where a container would outweigh the code
Dependency injection vs similar approaches
| Approach | Who creates the dependency | How the class gets it | Main difference from DI |
|---|---|---|---|
| Dependency injection | The composition root or a container | Handed in through the constructor, a setter or a parameter | The reference point for this table |
| Service locator | A registry, configured at startup | The class asks a global: Locator.get(...) | Pull instead of push; dependencies are hidden again and every class depends on the locator |
| Singleton | The class itself, on first use | Class.getInstance() from anywhere | Global access and a fixed implementation; DI keeps "one instance" but drops the global |
| Factory Method, Abstract Factory | The factory | The class calls the factory when it needs a new object | Use a factory when the class must create objects at runtime (one per request or per row). The factory itself is usually injected |
| Strategy | The client | Handed to the context | Strategy is about interchangeable algorithms; DI is the usual way the chosen strategy arrives. Injecting a strategy is DI applied to Strategy |
Implementation
The scenario as a complete program: Gateway, Mailer and Clock interfaces, real and fake implementations, a CheckoutService that receives all three through its constructor, a composition root (main) that wires the real ones, and a unit test that is its own composition root with fakes and a fixed clock. The real classes only print or count; in a real app they would call Stripe and an SMTP server. In C++ the root owns every object and the service holds references, so the dependencies must outlive it.
from datetime import datetime
from typing import Protocol
class Gateway(Protocol):
def charge(self, amount: int) -> str: ...
class Mailer(Protocol):
def send(self, to: str, msg: str) -> None: ...
class Clock(Protocol):
def now(self) -> str: ...
# Real implementations (stand-ins for network calls).
class StripeGateway:
def __init__(self) -> None:
self._charges = 0
def charge(self, amount: int) -> str:
# A real class would send the amount to Stripe here.
self._charges += 1
return f"ch_{self._charges}"
class SmtpMailer:
def send(self, to: str, msg: str) -> None:
# A real class would open an SMTP connection here.
print(f"mail to {to}: {msg}")
class SystemClock:
def now(self) -> str:
return datetime.now().strftime("%H:%M")
# The service: every collaborator arrives through the constructor.
class CheckoutService:
def __init__(self, gateway: Gateway, mailer: Mailer,
clock: Clock) -> None:
self._gateway = gateway
self._mailer = mailer
self._clock = clock
def checkout(self, amount: int, to: str) -> str:
time = self._clock.now()
charge_id = self._gateway.charge(amount)
msg = f"{charge_id} at {time}"
self._mailer.send(to, msg)
return msg
# Test doubles.
class FakeGateway:
def __init__(self) -> None:
self.charges: list[int] = []
def charge(self, amount: int) -> str:
self.charges.append(amount)
return f"fake_{len(self.charges)}"
class FakeMailer:
def __init__(self) -> None:
self.sent: list[str] = []
def send(self, to: str, msg: str) -> None:
self.sent.append(to)
class FixedClock:
def __init__(self, time: str) -> None:
self._time = time
def now(self) -> str:
return self._time
# A unit test is a composition root of its own.
def test_checkout() -> None:
pay = FakeGateway()
mail = FakeMailer()
svc = CheckoutService(pay, mail, FixedClock("09:00"))
r = svc.checkout(499, "qa@test")
assert r == "fake_1 at 09:00"
assert pay.charges == [499]
assert mail.sent == ["qa@test"]
print("test passed")
# Composition root: the only code that names concrete classes.
def main() -> None:
svc = CheckoutService(StripeGateway(), SmtpMailer(), SystemClock())
print(svc.checkout(499, "asha@ok")) # ch_1 at <current time>
if __name__ == "__main__":
main()
test_checkout()Key takeaways
- Dependency injection separates using an object from creating it: a class declares what it needs (usually in its constructor, as interfaces) and something outside passes it in.
- The composition root (
main, startup code or a container's configuration) is the one place that builds the object graph and names concrete classes; business classes never do. - Injection makes dependencies visible and replaceable. In the visualizer the same
CheckoutServicecharges Stripe in production and records[499]in a fake during the test, with a fixed clock making the receipt deterministic. - Prefer constructor injection for required dependencies; use setters only for optional ones and method parameters for per-call ones. A long constructor is a signal to split the class.
- Lifetimes (singleton, scoped, transient) are decided at the root. A dependency must live at least as long as the object that holds it, or you get a captive dependency.
- DI is a technique, DIP a principle and IoC the general idea; a service locator also supplies dependencies but hides them again. A container is optional: pure DI is DI too.
Common pitfalls
- Replacing
newwith a service locator or a global container lookup inside classes. The dependencies are hidden again, and every class now depends on the locator. - The captive dependency: injecting a scoped or transient object (a database session, the current user) into a singleton, which then keeps the first one forever and may share it across threads.
- Over-injection hidden instead of fixed: switching to field or setter injection to make a ten-parameter constructor look smaller. Split the class by responsibility instead.
- Calling the container from business code (
container.resolve(...)deep in a method). Only the composition root and framework entry points should touch the container. - Fakes that do not behave like the real thing: a fake gateway that never declines, or a fake clock nobody advances. Tests pass while the code under test is wrong; keep fakes small, honest and tested against the same contract.
Interview tips
- When an interviewer asks how you would test a class that sends email, charges cards or reads the clock, answer with constructor injection of an interface and a fake, then show the composition root that wires the real ones.
- Expect "DI vs DIP vs IoC" and "why is service locator an anti-pattern?". Answer with a technique, a principle and a general idea, then with hidden dependencies and global state.
- In LLD rounds, inject the volatile parts (
PaymentGateway,NotificationSender,Clock, repositories) into your services and say where they are wired. It shows testability and extension points without extra classes. - If asked about lifetimes, name singleton, scoped and transient, give one use of each, and mention the captive dependency rule.
Real-world applications
- Web frameworks that build controllers and services per request: Spring, ASP.NET Core, NestJS, Angular, FastAPI.
- Unit tests that replace payment, email, storage and HTTP clients with fakes, and the clock with a fixed one.
- Choosing implementations per environment: a sandbox payment gateway in staging, an in-memory queue in local development.
- Hexagonal and clean architectures (Layered, Hexagonal & Clean Architecture): adapters are injected into the domain's ports at the composition root.
- Plugin systems and feature flags, where the root picks which implementation of an interface to wire at startup.
- Sharing one expensive object (a connection pool, an HTTP client) across many services without a global Singleton.
Test yourself
In the visualizer's Production scenario With DI, which code creates stripe, smtp and clock?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.