7
Back to Boss Battles

DIVSIoC / DIP

The Problem

Scenario A β€” DI (the technique): Your OrderService needs a PaymentGateway. Instead of creating new StripeGateway() inside the service, you pass it via the constructor. Now tests can inject a mock. This is Dependency Injection β€” the mechanical act of passing dependencies in.

Scenario B β€” DIP (the principle): Your OrderService imports and directly depends on StripeGateway (a concrete class). Changing to Razorpay means editing OrderService. DIP says: both OrderService and StripeGateway should depend on an abstraction (PaymentGateway interface). The high-level module doesn't depend on the low-level one β€” both depend on the interface.

Scenario C β€” IoC (the architectural inversion): In a plain script, your code calls a library: const result = lib.process(data). In NestJS, the framework calls your code: it instantiates your service, injects dependencies, and invokes your handlers. You didn't call new OrderService() β€” the framework did. Control is inverted.


Why They Look Alike

All three appear together. A NestJS @Injectable() service uses DI (constructor injection), follows DIP (depends on interfaces), and runs inside IoC (the container manages lifecycle). People use the terms interchangeably because they usually coexist.

Rendering diagram…

They are related but operate at different levels: DIP is a design principle, DI is a coding technique, IoC is an architectural pattern.


The Core Difference

AspectDI (Dependency Injection)DIP (Dependency Inversion Principle)IoC (Inversion of Control)
What it isA technique: pass dependencies from outsideA SOLID principle: depend on abstractions, not concretionsAn architectural principle: framework controls the flow
LevelCode-level (constructor, setter)Design-level (interface direction)Architecture-level (who calls whom)
Without the othersYou can DI without DIP (inject a concrete class)You can follow DIP without DI (use a factory)You can have IoC without DI (event loop, callbacks)
Exampleconstructor(private gateway: StripeGateway)constructor(private gateway: PaymentGateway) (interface)NestJS creating and wiring your services automatically
BenefitTestability, swappabilityDecoupling, direction of dependency points toward stable abstractionsDeveloper writes business logic, framework handles plumbing

One sentence: DIP says "depend on abstractions." DI is how you pass them in. IoC is the framework that automates the wiring.


Side-by-Side Code

DI without DIP β€” Injecting a concrete class

typescript
1// DI is happening (dependency passed in), but DIP is violated
2// (OrderService depends on the concrete StripeGateway)
3class OrderService {
4 constructor(private gateway: StripeGateway) {} // concrete!
5
6 async checkout(order: Order): Promise<void> {
7 await this.gateway.charge(order.total, order.currency);
8 }
9}
10
11// Test: you CAN inject a different StripeGateway instance,
12// but you can't inject a RazorpayGateway without changing the type.

DI + DIP β€” Injecting an abstraction

typescript
1// Now both high-level (OrderService) and low-level (StripeGateway)
2// depend on the abstraction (PaymentGateway interface)
3interface PaymentGateway {
4 charge(amount: number, currency: string): Promise<{ txId: string }>;
5}
6
7class OrderService {
8 constructor(private gateway: PaymentGateway) {} // interface!
9
10 async checkout(order: Order): Promise<void> {
11 await this.gateway.charge(order.total, order.currency);
12 }
13}
14
15class StripeGateway implements PaymentGateway {
16 async charge(amount: number, currency: string) {
17 return { txId: `stripe_${Date.now()}` };
18 }
19}
20
21// Test: inject anything that satisfies PaymentGateway
22const mockGateway: PaymentGateway = { charge: async () => ({ txId: 'mock' }) };
23const svc = new OrderService(mockGateway);

IoC β€” NestJS container manages everything

typescript
1// You never call `new OrderService(new StripeGateway())`.
2// The container reads the dependency graph and wires it.
3
4@Injectable()
5class StripeGateway implements PaymentGateway {
6 async charge(amount: number, currency: string) {
7 return { txId: `stripe_${Date.now()}` };
8 }
9}
10
11@Injectable()
12class OrderService {
13 constructor(@Inject('PaymentGateway') private gateway: PaymentGateway) {}
14
15 async checkout(order: Order): Promise<void> {
16 await this.gateway.charge(order.total, order.currency);
17 }
18}
19
20@Module({
21 providers: [
22 OrderService,
23 { provide: 'PaymentGateway', useClass: StripeGateway },
24 ],
25})
26class OrderModule {}
27
28// IoC: NestJS instantiates StripeGateway, injects it into OrderService,
29// manages their lifecycle. You wrote the classes; the framework runs them.

Decision Rules

SignalChoose / ApplyWhy
"I want to pass a mock in tests"DIMechanical: accept dependency via constructor
"High-level modules should not import low-level modules"DIPDesign: introduce an interface between them
"I want the framework to wire everything automatically"IoC containerArchitecture: NestJS, Spring, Angular do this
"I'm writing a standalone script/CLI"DI (manual) is enoughNo container overhead needed
"I'm building a large app with 50+ services"IoC + DI + DIP togetherThe trio scales; manual wiring doesn't
"I have a factory creating the right implementation"DIP without DIFactory achieves inversion without injecting

The Trick Question

"Your NestJS service uses @Injectable() and accepts dependencies via constructor. A colleague says 'we're using Dependency Inversion.' Are they right?"

Not necessarily. If the constructor parameter is typed to a concrete class (constructor(private stripe: StripeGateway)), you're using DI (the technique) but violating DIP (the principle). DIP requires the parameter to be an abstraction (PaymentGateway interface). NestJS gives you IoC (the container), DI is automatic, but DIP is a design choice you must make yourself by introducing interfaces.


Interview Angles

Q: Can you have DI without IoC? Yes. Manual DI: const svc = new OrderService(new StripeGateway()). You inject the dependency yourself in the composition root. No framework, no container. This is common in tests and simple apps.

Q: Can you have IoC without DI? Yes. The event loop is IoC β€” you register a callback, the runtime calls it. Express middleware: you register handlers, Express calls them. No constructor injection involved.

Q: What's the Service Locator anti-pattern, and how does it relate? Service Locator is "ask a registry for your dependency" inside the class: this.gateway = ServiceLocator.get('PaymentGateway'). It hides dependencies (not in the constructor signature) and makes testing harder. DI makes dependencies explicit in the constructor β€” visible, mockable, analyzable.

Q: How do you explain all three in 30 seconds? "DIP is the SOLID rule: depend on abstractions, not concrete classes. DI is the technique: pass dependencies through the constructor instead of creating them inside. IoC is the architecture: a container or framework that automates the wiring so you don't manually construct and connect every object."