Dependency Injection – Should DI/IoC Remove All ‘New’ Keywords?

dependency-injectionioc-containersnet

Should the usage of Dependency Injection and an Inversion of Control container remove all occurrences of the "new" keyword from your code?

In other words, should every object/dependency, no matter how simple or short-lived, be "registered" within your IoC container and injected into the method/class that needs to use them?

If no, where do you draw the line between which dependencies/objects get registered in the IoC container, versus what gets created "in-line" as a concrete reference, via the new keyword ?

Best Answer

Avoid dogma. Do what feels right.

I prefer to use "new" for data structures which have no behavior.

If the class does have behavior, I then look at the scope of that behavior. If it is stateless and has no dependencies, I lean towards "new". I only begin refactoring towards DI when I need to add a dependency to stateful resources (such as a database or a file), or to other classes with such resources.

Related Topic