DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Dependency Injection in javascript

Dependency Injection (DI) is a design pattern that promotes the separation of concerns and helps to make your code more modular, flexible, and testable. In JavaScript, particularly in environments like Node.js or frontend frameworks (e.g., Angular), you can implement dependency injection in various ways.

Here's a basic explanation and example of dependency injection in JavaScript:

Dependency Injection Basics:
Dependency:
A dependency is an external module, service, or object that a function or module relies on to perform its task.

Injection:
Injection is the process of providing dependencies to a module or function from the outside, rather than having the module or function create the dependencies itself.

// Service module (dependency)
class Logger {
  log(message) {
    console.log(`[LOG] ${message}`);
  }
}

// Client module (dependent on Logger)
class OrderProcessor {
  constructor(logger) {
    this.logger = logger;
  }

  process(order) {
    this.logger.log(`Processing order: ${order}`);
    // Business logic for processing the order goes here
  }
}

// Dependency Injection
const logger = new Logger(); // Create an instance of the Logger
const orderProcessor = new OrderProcessor(logger); // Inject the logger into the OrderProcessor

// Now, you can use orderProcessor to process orders, and it will use the injected logger for logging.
orderProcessor.process('Order123');


Enter fullscreen mode Exit fullscreen mode

In this example, OrderProcessor is dependent on Logger, but instead of creating an instance of Logger inside OrderProcessor, we pass an instance of Logger to OrderProcessor when creating it. This is the essence of dependency injection.

Benefits of Dependency Injection:
Testability:
By injecting dependencies, you can easily replace them with mock objects or test doubles during unit testing.

Flexibility:
You can change the behavior of a module by injecting different implementations of its dependencies.

Modularity:
Dependencies are clearly defined and can be easily replaced or extended without modifying the dependent modules.

Top comments (0)