HomeToolsAbout a20k

Dependency Injection

Context

Inversify is a lightweight inversion of control (IoC) container.

IoC Container

IoC container uses a class constructor to identify and inject its dependencies.

Dependency

When you need another piece of code to run the current code

A relies on B 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

Common dependency

  • User model needs to talk to a database
    • Database used in User model is MySQL
      • persist method is called to store data into MySQL
public class User { MySqlDatabase database; public User() { database = new MySqlDatabase(); } public void() add(String data) { database.persist(data); } }

Inversion of Control

What is it

IoC is flipping of dependency

  • It's inverse in regards to procedural programming flow of control

Back to the example

If you were using a User container

  • Instead of defining the type of database used in the User class directly as concrete implementation
    • You instantiate the User
      • which is passed the Database type to be implemented as part of User
// previously user = container.new User(); public class User { database = MySqlDatabase(); } // dependency inversion user = container.new User(MySql()); public class User { this.database = database }

What did this inversion accomplish

  • Allows more abstraction over concrete implementation
  • loosely coupled architecture, plug-ability, flexibility
  • allows for handling of things like changing parameter or database types from specific implementation

Not solidifying concrete implementation choice now which will become harder to rip out or change when the codebase grows large and requirements change

Injection

Injection is when you pass something into the code instead of using it directly

"inject a code you need into another code"

  • passing the concrete decision as a parameter
  • remove direct dependencies between components by injecting their dependencies from external sources

Using Constructor

class UserService { constructor(database) { this.database = database; } // ... } const database = new Database(); const userService = new UserService(database);

Can also use setter

  • Illustration skipped as it is not recommended

Dependency Injection

depend upon abstractions and not depend upon concretions via passing/injection of concrete implementation to the abstraction as a parameter

© VincentVanKoh