Inversify is a lightweight inversion of control (IoC) container.
IoC container uses a class constructor to identify and inject its dependencies.
When you need another piece of code to run the current code
A
relies onB
to work
class A
uses methods from class B
= class A
is dependent of class B
class A needs to have instance or copy of B inside of A to work
User
model is MySQL
persist
method is called to store data into MySQLpublic class User { MySqlDatabase database; public User() { database = new MySqlDatabase(); } public void() add(String data) { database.persist(data); } }
IoC is flipping of dependency
If you were using a User container
// previously user = container.new User(); public class User { database = MySqlDatabase(); } // dependency inversion user = container.new User(MySql()); public class User { this.database = database }
Not solidifying concrete implementation choice now which will become harder to rip out or change when the codebase grows large and requirements change
Injection is when you pass something into the code instead of using it directly
"inject a code you need into another code"
class UserService { constructor(database) { this.database = database; } // ... } const database = new Database(); const userService = new UserService(database);
depend upon abstractions and not depend upon concretions via passing/injection of concrete implementation to the abstraction as a parameter