Overview

Supply dependencies from external sources

Dependency Injection 2 implementations available

When to Use

Available Implementations

Basic Example

// Dependency Injection implementation example
// This shows the basic structure of dependency injection in Express.js

// Define your interface
interface IRepository {
  findAll(): Promise<T[]>;
  findById(id: string): Promise<T | null>;
  create(data: CreateDto): Promise<T>;
  update(id: string, data: UpdateDto): Promise<T>;
  delete(id: string): Promise<void>;
}

// Implement the pattern
class DependencyRepository implements IRepository {
  async findAll(): Promise<T[]> {
    // Implementation
  }

  async findById(id: string): Promise<T | null> {
    // Implementation
  }

  async create(data: CreateDto): Promise<T> {
    // Implementation
  }

  async update(id: string, data: UpdateDto): Promise<T> {
    // Implementation
  }

  async delete(id: string): Promise<void> {
    // Implementation
  }
}

// Use the pattern
const repository = new DependencyRepository();
const items = await repository.findAll();

Frequently Asked Questions

What is Dependency Injection?
Supply dependencies from external sources. It's a well-established software design pattern that helps organize code for better maintainability and testability.
How does Dependency Injection work with Express.js?
Express.js provides excellent support for this pattern through its dependency injection system and middleware composition.
What are the benefits?
Improved testability, separation of concerns, easier maintenance, and flexibility to change implementations without affecting business logic.
When should I avoid this pattern?
For very simple applications with minimal logic, the pattern may add unnecessary complexity. Use judgment based on project requirements.