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

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


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.