Patrón de diseño donde las dependencias de un componente se pasan desde fuera.
En lugar de crearlas internamente. Facilita el testeo y la reutilización de código permitiendo intercambiar implementaciones.
// Sin DI - difícil de testear class UserService { private db = new PostgresDatabase(); // Acoplado async getUser(id: string) { return this.db.query(`SELECT * FROM users WHERE id = ${id}`); } } // Con DI - fácil de testear y flexible interface Database { query(sql: string): Promise<any>; } class UserService { constructor(private db: Database) {} // Inyectada async getUser(id: string) { return this.db.query(`SELECT * FROM users WHERE id = ${id}`); } } // Producción const realDb = new PostgresDatabase(); const userService = new UserService(realDb); // Tests const mockDb: Database = { query: jest.fn().mockResolvedValue({ id: '1', name: 'Test' }) }; const testService = new UserService(mockDb); // Framework DI (NestJS) @Injectable() class UserService { constructor(private readonly prisma: PrismaService) {} }