Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a project that uses a DI framework, should you NEVER use the 'new' operator?

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?

like image 221
Chuck Avatar asked Mar 28 '10 16:03

Chuck


People also ask

What is a DI framework?

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.

Why should we use DI?

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.

What is DI framework in Java?

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.

How do dependency injection frameworks work?

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.


3 Answers

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.

like image 115
duffymo Avatar answered Sep 19 '22 15:09

duffymo


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.

like image 43
Ben Lings Avatar answered Sep 21 '22 15:09

Ben Lings


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.

like image 30
Hans Wagner Avatar answered Sep 21 '22 15:09

Hans Wagner