[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,90 +2,174 @@
|
||||
id: wiki-2026-0508-dependency-injection-의존성-주입
|
||||
title: Dependency Injection (의존성 주입)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [DI, Dependency Injection, IoC, Inversion of Control]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.93
|
||||
verification_status: applied
|
||||
tags: [di, ioc, design-pattern, spring, nestjs]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: nestjs
|
||||
---
|
||||
|
||||
# [[Dependency Injection (의존성 주입)]]
|
||||
# Dependency Injection (의존성 주입)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
의존성 주입(Dependency Injection)은 프로그램의 규모가 커짐에 따라 모듈 간의 의존성을 리팩토링할 때 서비스 로케이터(Service Locator)와 함께 도입할 수 있는 설계 패턴입니다 [1]. 이 패턴은 여러 팀에서 제공하는 모듈들을 동적으로 결합할 수 있게 해주어, 개발자가 전체 시스템을 다 이해하지 않고도 작은 부분을 수정할 수 있도록 돕습니다 [1]. 그 외 구체적인 개념에 대해서는 소스에 관련 정보가 부족합니다.
|
||||
## 매 한 줄
|
||||
> **"매 의존성 매 외부 주입, 직접 생성 X"**. IoC 의 가장 흔한 구현. Martin Fowler (2004) 가 명명. 2026 현재 Spring (Java), NestJS (Node), Angular, dagger (Android), wire (Go) 매 mainstream; testability + decoupling 의 backbone.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **모듈 의존성 리팩토링의 일환:** 프로그램이 성장함에 따라 모듈을 분리하는 것은 필수적이며, 프레젠테이션-도메인-데이터(Presentation-Domain-Data) 계층화를 활용해 프로그램을 나눈 뒤 모듈 간의 의존성을 해결하는 과정에서 의존성 주입 패턴이 활용될 수 있습니다 [1].
|
||||
* **다양한 언어에서의 적용:** 이 패턴은 자바(Java)나 클래스 개념이 없는 자바스크립트(JavaScript) 스타일 등 각기 다른 프로그래밍 언어 환경에 모두 적용될 수 있으나, 언어의 특성에 따라 그 구현 형태는 다르게 나타납니다 [1].
|
||||
* 그 외 상세한 동작 원리나 구체적 구현 사례에 대해서는 소스에 관련 정보가 부족합니다.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
소스에 관련 정보가 부족합니다.
|
||||
### 매 형태 (3 종류)
|
||||
- **Constructor injection** — 생성자 매 dependency 받음. 매 immutable, 매 권장.
|
||||
- **Setter injection** — setter 매 dependency 받음. optional dep 에 적합.
|
||||
- **Field injection** — 매 framework 의 reflection. simple 하지만 testability ↓.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-03*
|
||||
### 매 benefit
|
||||
- **Testability** — mock 매 쉽게 inject.
|
||||
- **Decoupling** — concrete impl 의 unaware.
|
||||
- **Lifecycle 관리** — singleton, request-scoped, transient.
|
||||
- **Configuration centralization** — DI container 의 wiring.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Spring `@Autowired`, `@Component`.
|
||||
2. NestJS `@Injectable()` + module providers.
|
||||
3. Angular `providedIn: 'root'`.
|
||||
4. Go: 매 manual 또는 google/wire codegen.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### NestJS — constructor injection
|
||||
```typescript
|
||||
@Injectable()
|
||||
export class UserService {
|
||||
constructor(
|
||||
private readonly repo: UserRepository,
|
||||
private readonly logger: Logger,
|
||||
) {}
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
async find(id: string) {
|
||||
this.logger.log(`finding ${id}`);
|
||||
return this.repo.findById(id);
|
||||
}
|
||||
}
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
|
||||
- **Parent:** [[10_Wiki/Topics]]
|
||||
- **Related:** *(TODO: 최소 2개)*
|
||||
- **Opposite / Trade-off:** *(TODO)*
|
||||
- **Raw Source:** 직접 입력
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
@Module({
|
||||
providers: [UserService, UserRepository, Logger],
|
||||
exports: [UserService],
|
||||
})
|
||||
export class UserModule {}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Spring Boot — constructor injection (no `@Autowired` needed)
|
||||
```java
|
||||
@Service
|
||||
public class OrderService {
|
||||
private final PaymentGateway gateway;
|
||||
private final OrderRepository repo;
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
public OrderService(PaymentGateway gateway, OrderRepository repo) {
|
||||
this.gateway = gateway;
|
||||
this.repo = repo;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Token / interface binding (NestJS)
|
||||
```typescript
|
||||
export const PAYMENT_GATEWAY = Symbol('PAYMENT_GATEWAY');
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
@Module({
|
||||
providers: [
|
||||
{ provide: PAYMENT_GATEWAY, useClass: StripeGateway },
|
||||
],
|
||||
exports: [PAYMENT_GATEWAY],
|
||||
})
|
||||
export class PaymentModule {}
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
@Injectable()
|
||||
class CheckoutService {
|
||||
constructor(@Inject(PAYMENT_GATEWAY) private gw: PaymentGateway) {}
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Factory provider (async, e.g. DB connection)
|
||||
```typescript
|
||||
{
|
||||
provide: 'DATABASE_CONNECTION',
|
||||
useFactory: async (config: ConfigService) => {
|
||||
return await createPool({ url: config.get('DB_URL') });
|
||||
},
|
||||
inject: [ConfigService],
|
||||
}
|
||||
```
|
||||
|
||||
### Manual DI (Go, wire-style)
|
||||
```go
|
||||
// wire.go (codegen)
|
||||
func InitializeApp() *App {
|
||||
repo := NewUserRepo(NewDB())
|
||||
svc := NewUserService(repo)
|
||||
return NewApp(svc)
|
||||
}
|
||||
```
|
||||
|
||||
### Test with mock (vitest)
|
||||
```typescript
|
||||
const mockRepo: UserRepository = {
|
||||
findById: vi.fn().mockResolvedValue({ id: '1', name: 'A' }),
|
||||
};
|
||||
const service = new UserService(mockRepo, mockLogger);
|
||||
expect(await service.find('1')).toEqual({ id: '1', name: 'A' });
|
||||
```
|
||||
|
||||
### Modern: TC39 decorators + Reflect.metadata (2026)
|
||||
```typescript
|
||||
@injectable()
|
||||
class EmailService {
|
||||
@inject(SMTP_CLIENT) private smtp!: SmtpClient;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Spring/Java | `@Component` + constructor injection |
|
||||
| Node.js/TS, full framework | NestJS module providers |
|
||||
| Frontend (Angular) | `providedIn: 'root'` |
|
||||
| Go | manual or `google/wire` |
|
||||
| Tiny app, no framework | manual constructor — DI 불필요 |
|
||||
|
||||
**기본값**: constructor injection, framework-managed singleton. Field injection 매 피하기.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Inversion of Control]] · [[SOLID]] (D)
|
||||
- 변형: [[Service Locator]] · [[Factory Pattern]]
|
||||
- 응용: [[Spring Framework]] · [[NestJS]] · [[Angular]]
|
||||
- Adjacent: [[Cross-Cutting Concerns]] · [[Aspect-Oriented Programming (AOP)]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: provider wiring 생성, mock 매 test 자동 생성, refactor field→constructor injection.
|
||||
**언제 X**: lifecycle / scope decision 매 architectural taste 필요.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Service Locator** — DI 와 혼동, dep 매 hidden.
|
||||
- **Field injection 남용** — test 시 reflection 필요, 매 fragile.
|
||||
- **Circular dep** — A→B→A. forwardRef 로 hack 보다 redesign.
|
||||
- **God container** — singleton 매 200개. module boundary 무시.
|
||||
- **`new` in business logic** — DI 의 의미 없음.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Fowler 2004 *Inversion of Control Containers and the Dependency Injection Pattern*, NestJS docs 2026).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with NestJS/Spring/Go patterns |
|
||||
|
||||
Reference in New Issue
Block a user