Table of Contents
What dependency injection does
How to do dependency injection?
Add dependency information
Service management
Module creation
Summary
Reference materials
Home Development Tools VSCode Briefly talk about the principle of dependency injection in VSCode

Briefly talk about the principle of dependency injection in VSCode

Feb 07, 2023 pm 06:18 PM
vscode front end visual studio code

This article will give you a brief analysis of the principle of dependency injection in VSCode. Let’s talk about what dependency injection does? How to do dependency injection? I hope to be helpful!

Briefly talk about the principle of dependency injection in VSCode

The team has been implementing "Dependency Injection" for a while, but every time it is used, it feels strange. There are many concepts that are always unclear: service id, service description symbols, service decorators, etc.

Maybe it’s because I don’t understand the principles, and it feels “virtual” when using it. Recently, I tried to clarify the principles by reading the source code of VS Code and the articles shared by team leaders. Here’s what I do A simple introduction to core logic.

What dependency injection does

Assume the following situation:

  • Service module A, dependent service B;

  • Service module B;

  • Function module Feature, dependent on services A and B;

According to the ordinary writing method, it is:

class B {}

class A {
    constructor() {
        // 在 A 的构造器中 new B
        this.b = new B();
    }
}

class Feature {
    constructor() {
        this.a = new A();
        this.b = new B();
    }
}

// 使用时
const feature = new Feature();
Copy after login

The code is simple and clear, but there are some problems. For example: if A and B that Feature depends on need to be the same instance, the above writing method will initialize two B instances. [Recommended learning: vscode tutorial, Programming teaching]

Simple modification:

class A {
    constructor(b: B) {
        this.b = b;
    }
}

class Feature {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
}

// 使用时
const b = new B();
const a = new A(b);
const feature = new Feature(a, b);
Copy after login

When a module is initialized, first externally The dependent modules are created and passed into the function module in the form of parameters. This way of writing is "Dependency Injection".

The problem with this way of writing is that in the form of manual parameter transfer, the order of new must be manually guaranteed, that is, instances of a and b must be obtained before new can be executed. Feature.

When dependencies become complex, it is likely that countless basic modules are needed before creating a functional module, and the complexity will be very high. Similar to this feeling:

Briefly talk about the principle of dependency injection in VSCode

Imagine a model: there is a module controller, or "service manager" to manage these dependencies:

class Feature {
    // 声明这个模块依赖 idA, idB
    idA
    idB
}

// 告知「服务管理器」,怎么找对应的模块
services[idA] = A;
services[idB] = B;

// 使用时
const feature = services.createInstance(Feature);
Copy after login

Isn't this service carrying the previous "manual" process?
When createInstance(Feature), analyze the modules that Feature depends on:

  • If the dependent module has not created an instance, recursively create the service instance and finally return;

  • If the module it depends on already has an instance, return the instance;

  • After finding everything, inject the Feature through the parameters to complete the initialization;
    VSCode implements exactly such a "dependency injection system".

How to do dependency injection?

To implement such a set of functions, roughly:

  • How does a class declare the service id it depends on, that is, given a class, how does the outside know? What services does he rely on?

  • How to manage management services?

  • How to create a module?

The following will implement the simplest model, covering the main process.

Add dependency information

How to brand a class and declare the services it depends on?
Abstract the problem again: How to add additional information to a class?
In fact, every class is a Function under es5, and each Function is just an Object in the final analysis. As long as you add a few fields to the Object to identify the required service ID, you can complete what you need. Function.
This can be easily done by writing the "Parameter Decorator":

// 参数装饰器 
const decorator = (
    target: Object, // 被装饰的目标,这里为 Feature
    propertyName: string, 
    index: number // 参数的位置索引
) => {
    target['deps'] = [{        index,        id: 'idA',    }];
}
class Feature {
    name = 'feature';
    a: any;
    constructor(
        // 参数装饰器
        @decorator a: any,
    ) {
        this.a = a;
    }
}
console.log('Feature.deps', Feature['deps']);
// [{ id: 'idA', index: 0 }]
Copy after login

In this way, the serviceId can be obtained through Feature (which will be called constructor ctor later).

Service management

Use Map for management, one id corresponds to one service ctor.

class A {
    name = 'a';
}

// 服务集
class ServiceCollection {
    // 服务集合
    // key 为服务标识
    // value 为 服务ctor
    private entries = new Map<string, any>();

    set(id: string, ctor: any) {
        this.entries.set(id, ctor);   
    }

    get(id: string): any {
        return this.entries.get(id);
    }
}

const services = new ServiceCollection();

// 声明服务 A id 为 idA
services.set(&#39;idA&#39;, A);
Copy after login

The schematic diagram is as follows:

Now, you can find the constructor of the dependent service through Feature

// 通过 Feature 找到所依赖的 A
const serviceId = Feature[&#39;deps&#39;][0].id; // idA
console.log(
    &#39;Feature.deps&#39;, 
    services.get(serviceId) // A
);
Copy after login

Module creation

The specific idea is:

  • If the dependent module has not yet created an instance, recursively create the service instance and finally return;

  • If the module it depends on already has an instance, return the instance;

  • After finding everything, inject the Feature through the parameters to complete the initialization;

Here is a simple demo, with only one layer of dependencies (that is, the dependent services do not depend on other services). To put it simply, there is no recursion capability:

class InstantiationService {
    services: ServiceCollection;

    constructor(services: ServiceCollection) {
        this.services = services;
    }

    createInstance(ctor: any) {
        // 1. 获取 ctor 依赖的 服务id
        // 结果为: [&#39;idA&#39;]
        const depIds = ctor[&#39;deps&#39;].map((item: any) => item.id);

        // 2. 获取服务 id 对应的 服务构造器
        // 结果为:[A]
        const depCtors = depIds.map((id: string) => services.get(id));

        // 3. 获取服务实例
        // 结果为: [ A { name: &#39;a&#39;} ]
        const args = depCtors.map((ctor: any) => new ctor());

        // 4. 依赖的服务作为参数注入,实例化所需要模块
        // 结果为:[ Feature { name: &#39;feature&#39;, a }]
        const result = new ctor(...args);

        return result;
    }
}

const instantiation = new InstantiationService(services);

// 使用时
const feature = instantiation.createInstance(Feature);
Copy after login

So far , the core process of dependency injection has been implemented. When you want to use Feature, you only need to call createInstance, regardless of whether the service it depends on has been initialized. instantiation does this for us.

Summary

This article simply implements a demo-level "dependency injection" model and simply implements:

  • What is needed for module declaration Dependency;

  • Service management;

  • Module creation;

Based on this, you can Expand some advanced functions:

  • Module creation (recursive): VSCode uses a stack diagram to do this, and the algorithm is not complicated;

  • Dependency collection: can be used to analyze the dependencies of each module and can detect whether there is a "cyclic dependency";

  • Module destruction: When the module is destroyed, the services it depends on are recursively destroyed Instance;

  • Delayed initialization: When creating a dependent service, choose to create a proxy, and the instance will only be created when it is actually used;

  • Asynchronous Dependency: How to execute the creation logic when the creation process of the dependent service is asynchronous;

Source code address See the code of this article here.
Complete Function Refer to the code written by VSCode for the entire dependency injection system. For advanced information, see here.

Reference materials

VS Code source code location: src/vs/platform/instantiation/common
This article draws on code ideas, and the naming is also highly consistent (manual dog head

For more knowledge about VSCode, please visit: vscode tutorial!!

The above is the detailed content of Briefly talk about the principle of dependency injection in VSCode. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

Understanding React's Primary Function: The Frontend Perspective Understanding React's Primary Function: The Frontend Perspective Apr 18, 2025 am 12:15 AM

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of ​​componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

vscode terminal usage tutorial vscode terminal usage tutorial Apr 15, 2025 pm 10:09 PM

vscode built-in terminal is a development tool that allows running commands and scripts within the editor to simplify the development process. How to use vscode terminal: Open the terminal with the shortcut key (Ctrl/Cmd). Enter a command or run the script. Use hotkeys (such as Ctrl L to clear the terminal). Change the working directory (such as the cd command). Advanced features include debug mode, automatic code snippet completion, and interactive command history.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to solve the problem of vscode Chinese annotations becoming question marks How to solve the problem of vscode Chinese annotations becoming question marks Apr 15, 2025 pm 11:36 PM

How to solve the problem that Chinese comments in Visual Studio Code become question marks: Check the file encoding and make sure it is "UTF-8 without BOM". Change the font to a font that supports Chinese characters, such as "Song Style" or "Microsoft Yahei". Reinstall the font. Enable Unicode support. Upgrade VSCode, restart the computer, and recreate the source file.

Common commands for vscode terminal Common commands for vscode terminal Apr 15, 2025 pm 10:06 PM

Common commands for VS Code terminals include: Clear the terminal screen (clear), list the current directory file (ls), change the current working directory (cd), print the current working directory path (pwd), create a new directory (mkdir), delete empty directory (rmdir), create a new file (touch) delete a file or directory (rm), copy a file or directory (cp), move or rename a file or directory (mv) display file content (cat) view file content and scroll (less) view file content only scroll down (more) display the first few lines of the file (head)

vscode terminal command cannot be used vscode terminal command cannot be used Apr 15, 2025 pm 10:03 PM

Causes and solutions for the VS Code terminal commands not available: The necessary tools are not installed (Windows: WSL; macOS: Xcode command line tools) Path configuration is wrong (add executable files to PATH environment variables) Permission issues (run VS Code as administrator) Firewall or proxy restrictions (check settings, unrestrictions) Terminal settings are incorrect (enable use of external terminals) VS Code installation is corrupt (reinstall or update) Terminal configuration is incompatible (try different terminal types or commands) Specific environment variables are missing (set necessary environment variables)

vscode Previous Next Shortcut Key vscode Previous Next Shortcut Key Apr 15, 2025 pm 10:51 PM

VS Code One-step/Next step shortcut key usage: One-step (backward): Windows/Linux: Ctrl ←; macOS: Cmd ←Next step (forward): Windows/Linux: Ctrl →; macOS: Cmd →

See all articles