🏗️ Architecture

Dependency Injection

Dependency Injection (DI)

A design pattern in which the dependencies (other objects) an object needs are injected from outside rather than created directly. It realizes the D (Dependency Inversion Principle) of the SOLID principles and greatly improves loose coupling, testability, and maintainability.

🔄 Before and After Applying DI

Applying dependency injection lowers the coupling of the code and makes testing easier.

❌ Without DI (Tight Coupling)
class UserService:
def __init__(self):
# Created directly - tight coupling
self.db = MySQLDatabase()
self.email = SmtpEmailService()

# Problems:
# - Code must be modified when replacing the DB
# - A real DB connection is required for testing
# - Mocks cannot be used
✅ With DI (Loose Coupling)
class UserService:
def __init__(self,
db: Database,
email: EmailService):
# Injected from outside
self.db = db
self.email = email

# Advantages:
# - Depends on interfaces
# - Easy unit testing by injecting mocks

📐 Core Principles: IoC and SOLID

🔃 IoC (Inversion of Control)

"Don't call us, we'll call you"

Inversion of Control. Instead of an object finding or creating its dependencies directly, the framework/container injects them. DI is a representative way to implement IoC.

📌 SOLID - D (DIP)

Dependency Inversion Principle

"High-level modules do not depend on low-level modules. Both depend on abstractions (interfaces)."

💉 Comparison of DI Types

Recommended
Setter Injection
Setter Injection
Dependencies are injected through setter methods. Suitable for optional dependencies.
✅ Optional dependencies possible
✅ Can be replaced at runtime
⚠️ Incomplete objects can be created
⚠️ Null checks required
Not recommended
Field Injection
Field Injection
Dependencies are injected directly into fields using @Autowired and the like. Concise, but has many drawbacks.
✅ Concise code
❌ Reflection required for testing
❌ Immutability cannot be guaranteed
❌ Circular references are hard to detect

🛠️ Comparison of DI Frameworks

Framework Language DI Method Main Annotations/Decorators
Spring Java Automatic injection (IoC container) @Autowired, @Component, @Service
NestJS TypeScript Constructor injection (metadata) @Injectable(), @Inject()
FastAPI Python Function parameters (Depends) Depends(), Type Hints
ASP.NET Core C# Built-in DI container AddScoped, AddSingleton, AddTransient
Wire Go Compile-time code generation wire.Build(), Provider Functions

💻 Actual Implementation Code

# Python: 수동 의존성 주입 패턴
from abc import ABC, abstractmethod
from typing import Protocol

# 1. 인터페이스(Protocol) 정의
class UserRepository(Protocol):
    def find_by_id(self, user_id: int) -> dict | None: ...
    def save(self, user: dict) -> None: ...

class EmailService(Protocol):
    def send(self, to: str, subject: str, body: str) -> bool: ...

# 2. 구현체
class PostgresUserRepository:
    def __init__(self, connection_string: str):
        self.conn = connection_string  # 실제로는 DB 연결

    def find_by_id(self, user_id: int) -> dict | None:
        return {"id": user_id, "name": "John"}

    def save(self, user: dict) -> None:
        print(f"Saving to Postgres: {user}")

class SmtpEmailService:
    def send(self, to: str, subject: str, body: str) -> bool:
        print(f"Sending email to {to}")
        return True

# 3. 서비스 - 생성자 주입 (권장)
class UserService:
    def __init__(
        self,
        user_repo: UserRepository,      # 인터페이스에 의존
        email_service: EmailService
    ):
        self._user_repo = user_repo     # 불변성을 위해 _prefix
        self._email_service = email_service

    def register_user(self, name: str, email: str) -> dict:
        user = {"name": name, "email": email}
        self._user_repo.save(user)
        self._email_service.send(email, "환영합니다!", "가입 감사합니다.")
        return user

# 4. 의존성 조립 (Composition Root)
def create_user_service() -> UserService:
    # 프로덕션 의존성
    repo = PostgresUserRepository("postgres://localhost/mydb")
    email = SmtpEmailService()
    return UserService(repo, email)

# 5. 테스트 - Mock 주입
class MockUserRepository:
    def find_by_id(self, user_id): return {"id": user_id}
    def save(self, user): pass

class MockEmailService:
    def __init__(self): self.sent = []
    def send(self, to, subject, body):
        self.sent.append((to, subject, body))
        return True

def test_register_user():
    # Mock 주입으로 격리된 단위 테스트
    mock_email = MockEmailService()
    service = UserService(MockUserRepository(), mock_email)

    user = service.register_user("테스트", "test@test.com")

    assert user["name"] == "테스트"
    assert len(mock_email.sent) == 1  # 이메일 전송 검증
# FastAPI: Depends를 활용한 의존성 주입
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Annotated

app = FastAPI()

# 1. 의존성 함수들
def get_db():
    """데이터베이스 세션 의존성"""
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: Session = Depends(get_db)
):
    """인증된 사용자 의존성"""
    user = decode_token(token, db)
    if not user:
        raise HTTPException(status_code=401)
    return user

# 2. 서비스 클래스 정의
class UserService:
    def __init__(self, db: Session):
        self.db = db

    def get_user(self, user_id: int):
        return self.db.query(User).filter(User.id == user_id).first()

    def create_user(self, user_data: UserCreate):
        user = User(**user_data.dict())
        self.db.add(user)
        self.db.commit()
        return user

# 3. 서비스 의존성 함수
def get_user_service(db: Session = Depends(get_db)) -> UserService:
    return UserService(db)

# Type Alias로 가독성 향상
UserServiceDep = Annotated[UserService, Depends(get_user_service)]
CurrentUserDep = Annotated[User, Depends(get_current_user)]

# 4. 엔드포인트에서 의존성 주입
@app.get("/users/{user_id}")
def read_user(
    user_id: int,
    service: UserServiceDep,           # 자동 주입
    current_user: CurrentUserDep       # 인증 체크 + 주입
):
    user = service.get_user(user_id)
    if not user:
        raise HTTPException(status_code=404)
    return user

@app.post("/users")
def create_user(
    user_data: UserCreate,
    service: UserServiceDep
):
    return service.create_user(user_data)

# 5. 테스트에서 의존성 오버라이드
from fastapi.testclient import TestClient

def override_get_db():
    return TestingSessionLocal()

def override_user_service():
    return MockUserService()

app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_user_service] = override_user_service

client = TestClient(app)
response = client.get("/users/1")
assert response.status_code == 200
// NestJS: 데코레이터 기반 의존성 주입
import { Injectable, Module, Controller, Get, Post, Body } from '@nestjs/common';

// 1. 인터페이스 정의
interface IUserRepository {
  findById(id: number): Promise<User | null>;
  save(user: User): Promise<User>;
}

interface IEmailService {
  send(to: string, subject: string, body: string): Promise<boolean>;
}

// 2. Repository 구현체
@Injectable()
class TypeOrmUserRepository implements IUserRepository {
  constructor(
    @InjectRepository(User)
    private userRepo: Repository<User>
  ) {}

  async findById(id: number): Promise<User | null> {
    return this.userRepo.findOne({ where: { id } });
  }

  async save(user: User): Promise<User> {
    return this.userRepo.save(user);
  }
}

// 3. Service - 생성자 주입
@Injectable()
class UserService {
  constructor(
    // 토큰 기반 주입으로 인터페이스 의존
    @Inject('USER_REPOSITORY')
    private readonly userRepo: IUserRepository,

    @Inject('EMAIL_SERVICE')
    private readonly emailService: IEmailService
  ) {}

  async registerUser(name: string, email: string): Promise<User> {
    const user = new User(name, email);
    await this.userRepo.save(user);
    await this.emailService.send(email, '환영합니다!', '가입 감사합니다.');
    return user;
  }
}

// 4. Controller
@Controller('users')
class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  async create(@Body() dto: CreateUserDto) {
    return this.userService.registerUser(dto.name, dto.email);
  }
}

// 5. Module - 의존성 등록
@Module({
  providers: [
    UserService,
    {
      provide: 'USER_REPOSITORY',
      useClass: TypeOrmUserRepository,
    },
    {
      provide: 'EMAIL_SERVICE',
      useClass: SmtpEmailService,
    },
  ],
  controllers: [UserController],
})
class UserModule {}

// 6. 테스트 - Mock Provider
const module = await Test.createTestingModule({
  providers: [
    UserService,
    {
      provide: 'USER_REPOSITORY',
      useValue: { findById: jest.fn(), save: jest.fn() },
    },
    {
      provide: 'EMAIL_SERVICE',
      useValue: { send: jest.fn().mockResolvedValue(true) },
    },
  ],
}).compile();

💬 Learning Through Conversation

👤
Junior Developer
Inside a service class new DatabaseConnection()Isn't it okay to create it directly with ? It looks simpler.
🏗️
Senior developer
Then how will you handle testing? Every unit test has to connect to a real database, and you also have to clean up the test data. With DI, you can inject a Mock object and test quickly without a DB.
👤
Junior Developer
Ah, so it's because of testing. But isn't @Autowired field injection the simplest?
🏗️
Senior developer
Field injection looks convenient, but it requires reflection for testing and makes it hard to detect circular references. Constructor Injectionis recommended. The dependencies are explicit, immutability is guaranteed with final, and the official Spring documentation also recommends this approach.
👤
Junior Developer
What if the constructor has 10 dependencies? It gets too long...
🏗️
Senior developer
That's not a DI problem, but a class with too many responsibilitiesis the signal! Split the class according to the Single Responsibility Principle (SRP). When the constructor gets complicated, ask yourself, "Isn't this class doing too much?"

⚠️ Cautions

🔄

Circular Dependency

If A depends on B and B depends on A, a circular dependency occurs. With constructor injection, it can be detected early through compile/runtime errors. Rather than using @Lazy, reconsider the design.

🔧

Over-Engineering (Excessive Abstraction)

There is no need to create an interface for every class. If there is only one implementation and no possibility of replacing it, depending on it directly is fine. Remember the YAGNI (You Aren't Gonna Need It) principle.

🎭

Overuse of Mocks

If everything is mocked, tests become tied to the implementation. Mock only external systems (DB, API) and test internal logic with real objects. The principle of "Mock only at the boundaries."

📦

Service Locator Anti-Pattern

Fetching dependencies at runtime, as in Container.get(UserService), hides the dependencies. Use constructor injection, where dependencies are made explicit at compile time.

📋 Real-World Application Cases

Achieving 90% Test Coverage
Success

Situation: Legacy code created DB connections directly, making unit testing impossible. A real DB was needed to run tests, and test execution took more than 30 minutes.

Application: Refactored with the Repository pattern + constructor injection. Defined interfaces and changed the code so that Mock objects could be injected.

Result: Unit test execution time reduced to 30 seconds. Test coverage 20% → 90%. Tests run automatically on every PR in the CI/CD pipeline.

Key point:

DI is the foundation of testable code. Mock injection builds a fast feedback loop without external dependencies.

Replacing the Payment System - Completed in 3 Days
Success

Situation: The existing payment API (PaymentGatewayA) had to be replaced with a new payment API (PaymentGatewayB). A gradual migration without service interruption was needed.

Application: Because the system was designed to depend on the PaymentService interface, only the new implementation was added. Configured A/B switching with a Feature Flag.

Result: Only the DI configuration changed, with no business logic changes. Gradual transition 1% → 10% → 100%. Rollback is also possible immediately with just a configuration change.

Key point:

If you depend on an interface, replacing the implementation becomes a "configuration change." A practical benefit of loose coupling.

Application Startup Failure Due to Circular Dependency
Failure

Situation: OrderService depended on InventoryService, and InventoryService depended on OrderService. It was not detected at compile time because field injection (@Autowired) was used.

Problem: The service went down in a production deployment due to a Spring Context initialization failure. It was temporarily resolved with @Lazy, but the root cause was not resolved.

Solution: Separated the common logic into a separate service to eliminate the circular dependency. Switched to constructor injection so the circular dependency is detected at compile time.

Lesson:

With constructor injection, circular dependencies are caught early as compile errors. @Lazy is not a solution but merely hides the symptom.

🧠 Comprehension Quiz

Q. Which of the following is NOT a main advantage of dependency injection (DI)?
A. Mock objects can be injected during unit testing
B. Runtime performance improves
C. Implementations are easy to replace
D. Coupling between classes is reduced
Answer: B

Dependency injection is unrelated to improving runtime performance. If anything, some overhead may arise from IoC container initialization, the use of reflection, and so on.

The actual advantages of DI are:
• Testability: Isolated unit tests are possible by injecting mocks
• Loose coupling: Depending on interfaces makes it easy to replace implementations
• Maintainability: Dependencies are explicitly revealed

🔗 Related Terms

📚 Learning Resources