G
G
Governor2022-02-14 19:44:11
Angular
Governor, 2022-02-14 19:44:11

What is the benefit of using dependency injection?

Hello.
Learning NestJS, topic: Providers .
I read that a provider is a class that (thanks to the @Injectable decorator) can be injected as a dependency into other classes.

That is, instead of this:

export class Service1 {
    private prop: PropType;

    constructor() {
        this.prop = new PropType();
    }
}


We get this code:
export class Service2 {
    constructor(private prop: PropType) {}
}


But I just don’t understand what is the advantage of this approach, because one line is saved, or am I not understanding something and there are still advantages?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
Sergey, 2022-02-14
@KingstonKMS

For example, there is a logger class. Instead of creating a separate instance of the logger in different classes, you can create one instance and inject it where needed.
Also, for example, a class for working with a database or an external service.

A
Alexey Yarkov, 2022-02-14
@yarkov

https://habr.com/en/post/651139/
Read at your leisure how Nest works from the inside

A
Anton Shvets, 2022-02-15
@Xuxicheta

In your example, the dependency is created inside the class, and in the example above, the dependency is already created and passed to the class when it is instantiated.
In Angular and Nest, the creation is managed by the injector, which not only creates, but also monitors child dependencies and creates them too, at the moment when they are needed.
Also, di provides more flexibility, the injector is a kind of external variable that can be substituted. Which is handy when testing or when used in context.

D
Django Almighty, 2022-02-16
@12345678XYU87654321

Imagine that you need 50 MB of RAM to create an instance of the propType class. And you will do this every time you need this class in any service. When using DI, the injector (dependency container) will do this once, and in subsequent calls to various services, you will receive in the constructor a ready-made and only object of the propType class instance. I hope I explained clearly.

M
MisterN, 2022-02-17
@MisterN

You know, patterns, solid, dependency inversion and stuff like that.
PropType can also have dependencies that suddenly require a dependency.
I won’t tell you about Nestya, but in Angular there is also trishaking of dependencies. However, I'm not sure that it now works the same way as before.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question