What is Dependency Injection? Explained with Examples

Introduction:
Imagine a coffee machine that has a water tank welded inside it. It works, but you can never swap the tank for a bigger one, you can’t clean it properly, and if it leaks you have to throw away the whole machine. A better design gives the machine a slot where you plug in a tank. The machine only cares that something supplies water. It does not care which tank it is.
Dependency Injection (DI) is the same idea applied to code. Instead of a class creating the objects it needs by itself, those objects are given to it from outside. That small change makes code easier to test, easier to change, and easier to understand.
DI is one of the most useful ideas in software design. Frameworks like Angular, NestJS, Spring and ASP.NET are built around it, but you don’t need any framework to use it. In this lesson we will learn what a dependency is, what goes wrong when classes create their own, the main ways to inject dependencies, how DI makes testing simple, and how to build a tiny DI container in about twenty lines.
It follows our lessons on the SOLID principles and design patterns. All examples are plain JavaScript and were run with Node.js; the comments show the real output.
Part 1: The Problem
1. What is a Dependency?:
A dependency is any object that another piece of code needs to do its job. An OrderService that sends a confirmation message after an order is placed depends on something that can send messages. A UserService that saves users depends on a database. A report that shows today’s date depends on a clock.
Dependencies are completely normal. Every useful program has them. The question is not whether you have dependencies, but who creates them.
2. Hard-Coded Dependencies:
Here is the most common way people first write it. The class creates its own dependency with new:
class EmailSender {
send(to, message) {
console.log(`Email to ${to}: ${message}`);
}
}
class OrderService {
constructor() {
this.notifier = new EmailSender(); // creates its own dependency
}
placeOrder(order) {
this.notifier.send(order.contact, `Order #${order.id} confirmed`);
return { id: order.id, status: "placed" };
}
}
new OrderService().placeOrder({ id: 101, contact: "sara@example.com" });
// Email to sara@example.com: Order #101 confirmed
It works, so what is the problem? Look at what OrderService is now stuck with:
- It is hard to test. Every test that places an order will try to send a real email. You cannot check what was sent without reading someone’s inbox.
- It is hard to change. If the business wants SMS confirmations instead, you have to edit
OrderService, even though nothing about placing orders changed. - It hides what it needs. Looking at
new OrderService(), you have no idea it sends emails. The dependency is buried inside the constructor. - It can’t share. If
EmailSenderneeds settings (an API key, a server address), every class that creates one must know those settings too.
The class is tightly coupled to one specific implementation, just like the welded water tank.
Part 2: The Solution
3. Constructor Injection:
The fix is simple: don’t create the dependency inside the class. Ask for it in the constructor and let the caller pass it in:
class OrderService {
constructor(notifier) {
this.notifier = notifier; // received, not created
}
placeOrder(order) {
this.notifier.send(order.contact, `Order #${order.id} confirmed`);
return { id: order.id, status: "placed" };
}
}
const service = new OrderService(new EmailSender());
console.log(service.placeOrder({ id: 102, contact: "ali@example.com" }));
// Email to ali@example.com: Order #102 confirmed
// { id: 102, status: 'placed' }
That is all dependency injection is. The behaviour is identical, but now OrderService no longer decides which notifier it uses. Whoever creates the service decides.
Constructor injection is the most common and usually the best form, because:
- The dependencies are visible in one place: the constructor’s parameters.
- The object is complete and ready to use as soon as it is created.
- It is impossible to forget a dependency, because you can’t build the object without it.
4. Swapping Implementations:
Because OrderService only calls notifier.send(to, message), any object with a send method will work. Adding SMS needs no change to OrderService at all:
class SmsSender {
send(to, message) {
console.log(`SMS to ${to}: ${message}`);
}
}
new OrderService(new SmsSender()).placeOrder({ id: 103, contact: "+91-98000-00000" });
// SMS to +91-98000-00000: Order #103 confirmed
This is the Dependency Inversion Principle, the “D” in SOLID, in action. The high-level code (placing orders) depends on an abstraction (“something that can send a message”), not on a concrete detail (email). In TypeScript or Java you would write that abstraction as an interface, such as interface Notifier { send(to: string, message: string): void }. In JavaScript the abstraction is just the shape of the object.
It also follows the Open/Closed Principle: OrderService is open to new kinds of notifiers but closed to modification.
5. Testing with a Fake:
This is where DI pays for itself. In a test we can pass a fake notifier that simply records what it was asked to send:
const { test } = require("node:test");
const assert = require("node:assert");
class FakeNotifier {
constructor() { this.sent = []; }
send(to, message) { this.sent.push({ to, message }); }
}
test("placing an order sends one confirmation", () => {
const fake = new FakeNotifier();
const service = new OrderService(fake);
const result = service.placeOrder({ id: 7, contact: "test@example.com" });
assert.deepStrictEqual(result, { id: 7, status: "placed" });
assert.deepStrictEqual(fake.sent, [
{ to: "test@example.com", message: "Order #7 confirmed" },
]);
});
// node --test
// ok 1 - placing an order sends one confirmation
// # pass 1
// # fail 0
No emails were sent, no network was used, and the test runs in milliseconds. We can also check exactly what would have been sent. With the hard-coded version from example 2, this test would be impossible without mocking the module system.
The same trick works for anything slow, random or external: databases, payment gateways, the current time, random numbers and HTTP calls.
Part 3: Other Ways to Inject
6. Setter and Method Injection:
Constructor injection covers most cases, but there are two other forms you will see.
Setter injection passes a dependency through a method after the object is created. It suits optional dependencies, such as a logger. Method injection passes the dependency only to the one method that needs it, which suits things that change on every call:
class ReportGenerator {
setLogger(logger) { // setter injection (optional)
this.logger = logger;
}
generate(rows, formatter) { // method injection
this.logger?.log(`Generating report with ${rows.length} rows`);
return rows.map(formatter).join("\n");
}
}
const report = new ReportGenerator();
report.setLogger(console);
console.log(report.generate(
[{ name: "Pen", price: 10 }, { name: "Book", price: 250 }],
(r) => `${r.name.padEnd(6)} ₹${r.price}`
));
// Generating report with 2 rows
// Pen ₹10
// Book ₹250
The ?. means the report still works when no logger was set. The downside of setter injection is that the object can exist in a half-configured state, so use it only for things that are truly optional.
7. Injecting into Functions:
DI is not only for classes. In functional JavaScript, the usual style is a factory function that receives its dependencies as an object and returns functions that use them:
function makeUserService({ db, clock }) {
return {
createUser(name) {
const user = { id: db.nextId(), name, createdAt: clock.now() };
db.save(user);
return user;
},
};
}
const memoryDb = {
rows: [],
nextId() { return this.rows.length + 1; },
save(row) { this.rows.push(row); },
};
const fixedClock = { now: () => "2026-01-01T00:00:00.000Z" };
const users = makeUserService({ db: memoryDb, clock: fixedClock });
console.log(users.createUser("Zara"));
// { id: 1, name: 'Zara', createdAt: '2026-01-01T00:00:00.000Z' }
console.log(users.createUser("Imran"));
// { id: 2, name: 'Imran', createdAt: '2026-01-01T00:00:00.000Z' }
Notice the clock. Code that calls new Date() directly gives a different result every time, which makes it hard to test. Injecting a clock makes the output predictable. In production you would pass { now: () => new Date().toISOString() } and a real database.
Passing an object ({ db, clock }) instead of separate arguments means the order doesn’t matter and the names document themselves.
8. Default Parameters (Use with Care):
A popular shortcut is to give the dependency a default value, so normal callers don’t have to pass anything while tests still can:
class OrderService {
constructor(notifier = new EmailSender()) {
this.notifier = notifier;
}
}
console.log(new OrderService().notifier.constructor.name);
// EmailSender
This is handy in small projects. Be aware that OrderService still knows about EmailSender and imports it, so it is only half decoupled. In larger applications, prefer wiring everything in one place, as the next example shows.
Part 4: Wiring It All Together
9. The Composition Root:
If classes no longer create their dependencies, someone must. The answer is a single place near the start of the program, called the composition root, where all the real objects are created and connected:
// main.js: the only file that knows the concrete classes
const notifier = new EmailSender();
const orderService = new OrderService(notifier);
const checkout = new CheckoutController(orderService);
app.post("/checkout", (req, res) => checkout.handle(req, res));
Every other file just receives what it needs. To switch the whole app from email to SMS, you change one line in one file. For many applications, this manual wiring (sometimes called “pure DI”) is all you ever need.
10. Building a Tiny DI Container:
When an application has dozens of services, writing the wiring by hand becomes repetitive. A DI container is an object that knows how to build each service and its dependencies on request. Here is a working one in about twenty lines:
class Container {
#factories = new Map();
#singletons = new Map();
register(name, factory, { singleton = false } = {}) {
this.#factories.set(name, { factory, singleton });
}
resolve(name) {
const entry = this.#factories.get(name);
if (!entry) throw new Error(`Nothing registered for "${name}"`);
if (!entry.singleton) return entry.factory(this);
if (!this.#singletons.has(name)) {
this.#singletons.set(name, entry.factory(this));
}
return this.#singletons.get(name);
}
}
Each service is registered with a factory: a function that receives the container and builds the service, resolving its own dependencies:
const container = new Container();
container.register("notifier", () => new EmailSender(), { singleton: true });
container.register("orderService", (c) => new OrderService(c.resolve("notifier")));
const a = container.resolve("orderService");
const b = container.resolve("orderService");
console.log(a === b); // false: a new OrderService each time
console.log(a.notifier === b.notifier); // true: one shared EmailSender
a.placeOrder({ id: 104, contact: "sara@example.com" });
// Email to sara@example.com: Order #104 confirmed
try {
container.resolve("paymentGateway");
} catch (e) {
console.log(e.message);
}
// Nothing registered for "paymentGateway"
This shows the two most common lifetimes:
- Transient: a new instance every time it is resolved (our
orderService). - Singleton: one instance shared by everyone (our
notifier). Good for things that are expensive to create or hold shared state, like a database connection pool.
Real containers, such as the ones in NestJS, Angular, InversifyJS or Spring, add more features: a scoped lifetime (one instance per HTTP request), automatic detection of constructor parameters, and errors for circular dependencies. But underneath, they do what our twenty lines do.
Part 5: Mistakes to Avoid
11. Common Pitfalls:
- The Service Locator trap. Passing the whole container into a class and letting it call
container.resolve()whenever it likes looks like DI, but it hides dependencies again. Only the composition root (and factories) should talk to the container. Classes should receive the exact objects they need. - Too many constructor parameters. If a class needs seven dependencies, DI isn’t the problem. The class is doing too much and should be split, following the Single Responsibility Principle.
- Injecting everything. Plain helper functions like
formatPrice()or values likeMath.PIdon’t need to be injected. Inject things that are external, slow, random, or likely to change: databases, network clients, clocks, loggers, payment and email providers. - Circular dependencies. If A needs B and B needs A, neither can be built first. This usually means some shared logic should move into a third class that both depend on.
- Using a framework too early. Start with constructor injection and manual wiring. Reach for a container only when the wiring becomes genuinely painful.
12. Real-World Example: Payments:
Here is how DI shows up in a typical online shop. A CheckoutService depends on a payment gateway, an inventory store and a notifier:
class CheckoutService {
constructor({ payments, inventory, notifier }) {
this.payments = payments;
this.inventory = inventory;
this.notifier = notifier;
}
}
- In production, the composition root passes a real Razorpay or Stripe client, a PostgreSQL inventory repository and an email sender.
- In local development, it passes a sandbox payment client and an SMS sender that just prints to the console.
- In tests, it passes fakes, so you can test “payment declined” or “item out of stock” without a real card or database.
CheckoutService itself is identical in all three. That is the real power of dependency injection: the business logic stays the same while the world around it changes.
Conclusion:
Dependency injection means giving an object the things it needs instead of letting it create them. We saw how hard-coded new calls make code hard to test and change, and how constructor injection fixes that with almost no extra code. We used fakes to test without sending real emails, injected a clock to make time predictable, wired the app in a composition root, and built a small container with transient and singleton lifetimes. We also covered the traps: the service locator, bloated constructors, and injecting things that don’t need it.
The idea is simple, but it connects directly to the SOLID principles, especially Dependency Inversion, and it is the foundation of almost every modern backend framework.
In the next lesson we will learn two classic design patterns that work beautifully with dependency injection: the Strategy and Observer patterns.


