How to read code that uses dependency injection
In NestJS, Angular, InversifyJS and similar frameworks, objects are wired up by a container, not by imports. How to find which implementation is actually used.
Dependency injection (DI) means a class receives the objects it needs instead of creating them. A container, configured somewhere else, decides which implementation to provide. That makes code easier to test and change, and harder to read: the class tells you it needs a PaymentService, but not which one it gets.
Recognise DI
- NestJS:
@Injectable()classes, constructor parameters,providersarrays in@Module - Angular:
@Injectable({ providedIn: 'root' }), constructor parameters orinject() - InversifyJS and tsyringe:
@injectable(),@inject(TOKEN), container bindings - AdonisJS: the IoC container and providers
- Hand-rolled: factory functions that pass dependencies into constructors
Find the binding, not just the type
When a constructor asks for PaymentService, find where the container is told what to provide for it. In NestJS, look for the module that lists it in providers. Watch for custom providers:
{ provide: PaymentService, useClass: StripePaymentService }
{ provide: 'CACHE', useFactory: () => createRedisCache(config) }useClass, useFactory, useValue and useExisting all substitute something other than the class name you see.
Check scope and lifetime
Containers can provide one shared instance (singleton), one per request, or a new one each time. In Angular, where a service is provided (root, a lazy-loaded route, a component) changes whether components share it. Scope explains many "why is this state shared?" puzzles.
Use tokens to search
String or symbol tokens (@Inject('CACHE')) are searchable. Search for the token everywhere: one place provides it, others inject it.
Watch for environment-specific wiring
Modules often provide different implementations by environment: a fake email sender in tests, a real one in production. Check for conditional provider configuration and module imports that depend on config.
Follow the module graph
In NestJS and Angular, a provider must be exported by its module and that module imported where it's used. The module graph tells you which implementations are visible where. Start from the root module and follow imports.
Ask which implementation runs
Ask RepoGrasp "which class is injected as PaymentService in OrdersController in production, and where is that configured?" It reads module and provider configuration across files and cites the binding. DI is runtime wiring, so confirm in a debugger if the configuration is dynamic.