Sobes.tech
Middle+

Как осуществляется передача зависимостей в конструкторы?

sobes.tech AI

Answer from AI

Dependencies are passed to constructors through their parameters. This is called Dependency Injection (DI).

There are three main ways to implement dependency injection:

  1. Through the constructor (Constructor Injection): Dependencies are passed as arguments to the constructor when creating an instance of the class.

    class Database {
      // ...
    }
    
    class UserRepository {
      constructor(db) { // Dependency Database is passed to the constructor
        this.db = db;
      }
      // ...
    }
    
    const db = new Database();
    const userRepository = new UserRepository(db); // Injecting dependency during object creation
    
  2. Through a setter (Setter Injection): Dependencies are passed via public setter methods after the class instance is created.

    class Database {
      // ...
    }
    
    class UserRepository {
      setDatabase(db) { // Setter method for dependency injection
        this.db = db;
      }
      // ...
    }
    
    const userRepository = new UserRepository();
    const db = new Database();
    userRepository.setDatabase(db); // Injecting dependency via setter
    
  3. Through properties (Property Injection): Dependencies are directly assigned to public properties of the object after its creation.

    class Database {
      // ...
    }
    
    class UserRepository {
      // public db; // Property for dependency
    
      constructor() {
        // ...
      }
      // ...
    }
    
    const userRepository = new UserRepository();
    const db = new Database();
    userRepository.db = db; // Injecting dependency via property
    

The most recommended method is constructor injection, as it guarantees the presence of all necessary dependencies when creating the object and makes dependencies clear. In some cases, setters or properties are used, for example, when injecting optional dependencies or in frameworks that utilize Property Injection.

Как осуществляется передача зависимостей в… - sobes.tech