Dependency Injection with Plain JavaScript
Dependency injection means providing dependencies to a component rather than having it construct them internally. This improves testability, flexibility, and separation of concerns.
JavaScript's functions and objects make dependency injection straightforward without requiring a framework.
Injecting a Repository
function createUserService(userRepository) {
return {
async getUser(id) {
return userRepository.findById(id);
}
};
}
const service = createUserService({
findById: async id => ({ id, name: 'Suriya' })
});💡 The service does not create the repository. A caller supplies it, making the service easier to test with a fake repository.
Key Takeaways
- Dependency injection separates construction from behavior.
- Functions can receive dependencies directly.
- Injected dependencies simplify unit testing.
Knowledge Check
What is the primary benefit of dependency injection?