Issue
i'm having some trouble in getting why breaking the rules is bad ))
import {DepClass} from './di-import' // <- some dependency imports here
class DI1 {
dep1: DepClass
constructor(){
this.dep1 = new DepClass() // <- bad
}
......
}
class DI2 {
dep2: DepClass
constructor(d: DepClass){ // <- slightly better
this.dep2 = d
}
......
}
so, i know, that class shouldn't create instances of its dependencies on its own, IoC rule breaks. But what's so terrible going on? What the overhead happens?
What is the working difference between "inline" creating an instance of Dependency in constructor and passing copy of already existing Dependency into constructor as a argument? Apart from the fact that both classes are working fine ))
Have one thought tho. Maybe, all of that is only needed for DI container properly working, it looks carefully at constructor arguments.
Thanks in advance
Solution
constructor(){
this.dep1 = new DepClass() // <- bad
}
Here you create a new instance of DepClass when you create an instance of the dependent class.
constructor(d: DepClass){ // <- slightly better
this.dep2 = d
}
Here the dependency injection framework instantiates a single DepClass for you, and provides it to any classes that want access to that instance.
If many classes depend on DepClass then, in the first example you would get many instances of that class created specifically during the construction of those objects.
In the second example only one single instance of DepClass is ever created, and it's shared after its construction with any class that declare it as a dependency.
Dependency injection doesn't look like a great idea with small contrived examples like this. But as your app scales up and you have dozens of classes that each have many dependencies, it starts to be a lot of useful to keep this clean.
Answered By - Alex Wayne
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.