Dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs.
Instead, the receiving "client" (object or function) is provided with its dependencies by external code (an "injector"), which it is not aware of.
Because dependency injection separates how objects are constructed from how they are used, it often diminishes the importance of the new keyword found in most object-oriented languages.
[13][14][15][16] As an analogy, cars can be thought of as services which perform the useful work of transporting people from one place to another.
Car engines can require gas, diesel or electricity, but this detail is unimportant to the client—a driver—who only cares if it can get them to their destination.
As such, which engine they were 'injected' with on the factory line ceases to matter and drivers can switch between any kind of car as needed.
[17][18] By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.
In Java, for example, reflection can make private attributes public when testing and inject services directly.
This could be acting as a factory or sub-assembler to resolve other dependencies, thus abstracting some details from the main assembler.
The simplest way of implementing dependency injection is to manually arrange services and clients, typically done at the program's root, where execution begins.
Manual dependency injection is often tedious and error-prone for larger projects, promoting the use of frameworks which automate the process.
[32][33] Some frameworks, like Spring, can use external configuration files to plan program composition: Even with a potentially long and complex object graph, the only class mentioned in code is the entry point, in this case Client.Client has not undergone any changes to work with Spring and remains a POJO.
[34][35][36] By keeping Spring-specific annotations and calls from spreading out among many classes, the system stays only loosely dependent on Spring.
We can then create a new injector that provides components defined in the myModule module, including the greeter service.
To avoid the service locator antipattern, AngularJS allows declarative notation in HTML templates which delegates creating components to the injector.
Finally you can use the database connection initialized in your main function at the data access layer: