ProgramGuru

Dependency Injection

Dependency Injection — purpose and prerequisites

Dependency injection supplies dependencies to a function or class instead of constructing them deep inside business logic. An interface describing what is needed lets production code use a database repository and tests use a small in-memory stand-in. Injection is a design choice; it does not require a dependency-injection framework.

What you’ll learn

  • Explain the purpose of dependency injection.
  • Identify the typed contract, runtime responsibilities and common pitfalls.
  • Run the example and extend its behavior with a practical exercise.

How the idea works

GreetingService asks its injected store for a user name. The tiny object satisfies UserStore structurally and makes the service predictable without any real database.

Dependency injection does not automatically make dependencies safe, scoped, or thread-safe; the application still owns construction and lifetime.

Visualize the flow

Dependency Injection — learning flowApp composition root → Injected UserStore → GreetingServiceDependency Injection1App composition root2Injected UserStore3GreetingServiceStatic contracts need runtime checks at external boundaries.
A three-step view of the responsibilities and the observable result.

Run the checked TypeScript example

This source was compiled using TypeScript 5.8.3 with strict checking, then executed with Node.js 22.16.0. Its stdout below is the actual captured output. The core logic is runnable without a framework or a remote API; integration-specific examples appear in a separate lab when needed.

TypeScript source

interface UserStore { findName(id: number): string | undefined }
class GreetingService {
  constructor(private readonly store: UserStore) {}
  greet(id: number): string {
    return `Hello, ${this.store.findName(id) ?? "guest"}`;
  }
}
const store: UserStore = { findName: id => id === 1 ? "Maya" : undefined };
console.log(new GreetingService(store).greet(1));
console.log(new GreetingService(store).greet(2));

Verified output

Hello, Maya
Hello, guest

Compile: npx tsc --strict --target es2022 --module commonjs dependency-injection.ts; run: node dependency-injection.js. For examples importing node: modules, install @types/node as a development dependency; for browser or React projects use the separate lab setup.

Trace the execution

GreetingService asks its injected store for a user name. The tiny object satisfies UserStore structurally and makes the service predictable without any real database.

Before editing the code, predict what the output will be for one changed input. Run it and compare your prediction with the actual result.

Common mistake and correction

Dependency injection does not automatically make dependencies safe, scoped, or thread-safe; the application still owns construction and lifetime.

Determine whether the issue belongs to the type system, a trust boundary, or actual runtime behavior before choosing a correction.

Your turn: extend the example

Write a second UserStore that holds a Map. Reuse GreetingService unchanged and test missing IDs.

Record expected success and failure outcomes, run the code, and compare the observed behavior. Keep the exercise compatible with strict type checking.

Check your understanding

Which statement correctly describes dependency injection in the example?
Choose one answer. You can try again.

Answer and explanation

GreetingService asks its injected store for a user name.

GreetingService asks its injected store for a user name. The tiny object satisfies UserStore structurally and makes the service predictable without any real database.

Key idea to remember

GreetingService asks its injected store for a user name. The tiny object satisfies UserStore structurally and makes the service predictable without any real database.

Apply the same reasoning to the practice task, then integrate it into a real app only when the runtime and dependency setup are ready.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Configuration Management →