Member-only story

Nodejs: Dependency Injection

Sunil Kumar
3 min readApr 24, 2023

--

Dependency Injection is a design pattern used in software engineering that helps to decouple the various components of an application by allowing objects to be created with their dependencies supplied from external sources rather than being created within the object itself.

In other words, Dependency Injection (DI) is a technique in which an object receives its dependencies from an external source, rather than creating them itself.

Here’s a working code example of dependency injection in Node.js using TypeScript:

// Define an interface for the database class
interface IDatabase {
save(data: any): Promise<void>;
}

// Define a class that implements the IDatabase interface
class Database implements IDatabase {
async save(data: any) {
// Save the data to the database
console.log('Data saved to the database:', data);
}
}

// Define a repository interface for the User model
interface IUserRepository {
save(user: any): Promise<void>;
}

// Define a class that implements the IUserRepository interface
class UserRepository implements IUserRepository {
constructor(private database: IDatabase) {}
async save(user: any) {
// Use the injected database instance to save the user
console.log('Saving user to the database...');
await this.database.save(user);
console.log('User saved to the database:', user);
}
}

// Define a…

--

--

Sunil Kumar
Sunil Kumar

Written by Sunil Kumar

With an extensive professional experience spanning over 16 years in the IT industry, I am a seasoned expert in AWS Cloud, DevOps, FastAPI, and Python.

No responses yet