I'm trying to wrap my head around Dependency Injection.
One of the things I'm confused about is whether all of your object instantiation needs to be controlled by the DI framework (Spring, Guice, etc).
Or, if not, how do you determine which objects are instantiated by the framework and which objects are instantiated with the new
operator?
Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.
The dependency injection technique enables you to improve this even further. It provides a way to separate the creation of an object from its usage. By doing that, you can replace a dependency without changing any code and it also reduces the boilerplate code in your business logic.
Dependency injection (DI) is the concept in which objects get other required objects from outside. DI can be implemented in any programming language. The general concept behind dependency injection is called Inversion of Control. A Java class has a dependency on another class, if it uses an instance of this class.
A DI framework will normally provide both object creation facilities (figure out the dependencies required for the constructor) as well as a Service Locator facility so that not everything has to be passed in the constructor or as a parameter to methods.
No, there's still a place for new. Not all objects need be under the DI factory's control.
You can easily spot the classes that need to be under the DI factory's control, because they usually involve interfaces and implementations.
Any local object in an implementation is entitled to call new. Model objects instantiated to satisfy a particular use case should be instantiated by calling new and passing the parameter values for that particular instance.
I've found this post by Miško Hevery very helpful in distinguishing between which objects should be injected as dependencies and which it's OK to create. He distinguishes between 'Newable' and 'Injectable' classes.
I'd say simpler Objects with no 'real' dependencies should not be injected. These could be data objects or, of course, exceptions and the like.
The 'eliminats the new operator' thing basically just gives a good guideline where to look for DI-able stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With