Many people come from frameworks that implement Dependency Injection and IoC containers for everything (in my case Angular 2+), so, this group of people will try to use dependency injection and IoC containers in everything even outside those frameworks.
But, most of the implementation using DI is not using it to implement the Dependency inversion principle from SOLID (which is kind of impossible to implement without DI), they are just using it as a way of making the class easily testable doing something like this:
class Dependency {}
class SomeClass {
constructor(private dependency: Dependency) {}
}
But why not this:
class Dependency {
static global = new Dependency();
}
class SomeClass {
protected dependency = Dependency.global;
}
We can easily mock/stub this dependecy only by extending it:
class TestSomeClass extends SomeClass {
protected dependency = mock<Dependency>();
}
Is there any problem we could face by doing this instead of dependency injection?
SomeClass objectUnderTest = new SomeClass(mock<Dependency>())
? – Filip Milovanović Dec 01 '23 at 15:02a IoC container or will need to have a class/file just to inject dependency or will need to pass dependency each time it needs to consume a class.
It's kind of add additional work that can be avoided if you are not depending on abstractions.
– Vitor Figueredo Marques Dec 01 '23 at 15:09But, injecting the same way @Doc Brown showed is really a better alternative.
– Vitor Figueredo Marques Dec 01 '23 at 15:30