Dependency Injection and Clean Architecture

Dependency injection means supplying dependencies to a component instead of having the component construct them directly. This reduces coupling and makes testing easier.

Clean architecture separates business rules from frameworks and infrastructure. The exact folder structure is less important than keeping dependencies pointing in sensible directions.

Simple Dependency Injection
interface UserRepository {
  findById(id: string): Promise<{ id: string; name: string } | null>;
}

class UserService {
  constructor(private readonly repository: UserRepository) {}

  getUser(id: string) {
    return this.repository.findById(id);
  }
}
💡 The service depends on an interface rather than a concrete database implementation, making it easier to test with a fake repository.
Key Takeaways
  • Dependency injection reduces tight coupling.
  • Business logic should not depend directly on infrastructure when avoidable.
  • Interfaces and dependency inversion can improve testability.
Knowledge Check

What is a major benefit of dependency injection?