75 lines
1.7 KiB
Markdown
75 lines
1.7 KiB
Markdown
# Simple Dependency Injection Container
|
|
|
|
A learning project to understand how Dependency Injection works by building one from scratch.
|
|
|
|
Inspired by the Phenix RTS platform's DI system.
|
|
|
|
## Learning Goals
|
|
|
|
1. Understand how DI containers resolve dependencies
|
|
2. Learn about different lifecycle patterns (singleton, transient, factory)
|
|
3. Understand circular dependency detection
|
|
4. Learn about provider patterns
|
|
5. Understand type registration and resolution
|
|
|
|
## Steps
|
|
|
|
We'll build this incrementally:
|
|
|
|
1. **Step 1**: Basic container with manual registration
|
|
2. **Step 2**: Constructor injection
|
|
3. **Step 3**: Singleton vs Transient lifecycles
|
|
4. **Step 4**: Circular dependency detection
|
|
5. **Step 5**: Provider pattern
|
|
6. **Step 6**: Named registrations
|
|
7. **Step 7**: Configuration-driven DI (like Phenix's di.json)
|
|
|
|
## Running the Examples
|
|
|
|
```bash
|
|
# Step 1 - Basic
|
|
node step1-basic.js
|
|
|
|
# Step 2 - Constructor Injection
|
|
node step2-constructor-injection.js
|
|
|
|
# Step 3 - Lifecycles
|
|
node step3-lifecycles.js
|
|
|
|
# Step 4 - Circular Dependencies
|
|
node step4-circular-deps.js
|
|
|
|
# Step 5 - Providers
|
|
node step5-providers.js
|
|
|
|
# Step 6 - Named Registrations
|
|
node step6-named.js
|
|
|
|
# Step 7 - Configuration
|
|
node step7-config.js
|
|
```
|
|
|
|
## Key Concepts
|
|
|
|
### Dependency Injection
|
|
|
|
Instead of creating dependencies inside a class, they are "injected" from outside.
|
|
|
|
### Inversion of Control (IoC)
|
|
|
|
The container controls object creation and lifecycle, not your code.
|
|
|
|
### Service Locator vs DI
|
|
|
|
DI is better because dependencies are explicit in constructor signatures.
|
|
|
|
## Architecture
|
|
|
|
```
|
|
Container
|
|
├── Registry (stores type registrations)
|
|
├── Resolver (resolves dependencies)
|
|
├── Lifecycle Manager (handles singleton/transient)
|
|
└── Provider System (custom creation logic)
|
|
```
|