We will start by defining what is the DI pattern and what is a good use-case for such a pattern. The main goal of this pattern is disconnecting the client from the knowledge of how to construct a service or an object it needs and letting someone else handle the construction (aka - Injector).

When you create an object within your class aka “newing it yourself” you bind your class to these objects making it impossible to switch implementations from outside of your code example - using configuration files (such as in Java beans and XML), meaning you will need to compile/deploy/build your codebase each time a change is needed. which means your class is not reusable since it is bound to a single implementation of that service/object.

This pattern can help solve answer some important questions/ goals such as:

  • How can an application or class be independent of how its objects are constructed?
  • Objects creation can now be specified in separate configuration files.
  • How can our application support different configurations?
  • Dependency injection makes testing easier - since now we can change the service to a mocker of the real service so we can control the results.

This pattern can help solve answer some important questions/goals such as:

  • How can an application or class be independent of how its objects are constructed?
  • Objects creation can now be specified in separate configuration files.
  • How can our application support different configurations?
  • Dependency injection makes testing easier - since now we can change the service to a mocker of the real service so we can control the results.

Typescript is great for implementing this design pattern and in this post, we will implement a simple DI system step by step. We will start by defining a constructible interface:

export interface Constructable<T=any> {
  new(...params): T;
}

#typescript #javascript

Creating your own Dependency Injector (DI) library – Typescript - JavaScript inDepth
1.40 GEEK