Home > Development Tools > VSCode > body text

Briefly talk about the principle of dependency injection in VSCode

青灯夜游
Release: 2023-02-20 19:39:58
forward
2058 people have browsed it

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!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template