Answer the question
In order to leave comments, you need to log in
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();
}
}
export class Service2 {
constructor(private prop: PropType) {}
}
Answer the question
In order to leave comments, you need to log in
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.
https://habr.com/en/post/651139/
Read at your leisure how Nest works from the inside
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.
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.
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 questionAsk a Question
731 491 924 answers to any question