ArticleslgStudy

computer science

Dependency injection

Dependency injection is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Dependency injection rather than just read about it. In short: In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs.

Dependency injection — main illustration
Dependency injection — illustration

Key takeaways

  • Dependency injection belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Dependency injection to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Dependency injection from memory before moving on to harder problems.

Reference excerpt

In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs. The pattern ensures that an object or function that wants to use a given service should not have to know how to construct those services. Instead, the receiving "client" (object or function) is provided with its dependencies by external code (an "injector"), which it is not aware of. Dependency injection makes implicit dependencies explicit and helps solve the following problems:

How can a class be independent from the creation of the objects it depends on? How can an application and the objects it uses support different configurations? Dependency injection is often used to keep code in-line with the dependency inversion principle. In statically typed languages using dependency injection means that a client only needs to declare the interfaces of the services it uses, rather than their concrete implementations, making it easier to change which services are used at runtime without recompiling. Application frameworks often combine dependency injection with inversion of control. Under inversion of control, the framework first constructs an object (such as a controller), and then passes control flow to it. With dependency injection, the framework also instantiates the dependencies declared by the application object (often in the constructor method's parameters), and passes the dependencies into the object. Dependency injection implements the idea of "inverting control over the implementations of dependencies", which is why certain Java frameworks generically name the concept "inversion of control" (not to be confused with inversion of control flow).

Roles

Dependency injection involves four roles: services, clients, interfaces, and injectors.

Services and clients A service is any class which contains useful functionality. In turn, a client is any class which uses services. The services that a client requires are the client's dependencies. Any object can be a service or a client; the names relate only to the role the objects play in an injection. The same object may even be both a client (it uses injected services) and a service (it is injected into other objects). Upon injection, the service is made part of the client's state, available for use.

Interfaces Clients should not know how their dependencies are implemented, only their names and API. A service which retrieves emails, for instance, may use the IMAP or POP3 protocols behind the scenes, but this detail is likely irrelevant to calling code that merely wants an email retrieved. By ignoring implementation details, clients do not need to change what their dependencies do.

Injectors The injector, sometimes also called an assembler, container, provider or factory, introduces services to the client. The role of injectors is to construct and connect complex object graphs, where objects may be both clients and services. The injector itself may be many objects working together, but must not be the client, as this would create a circular dependency. 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. Because the framework handles creating services, the programmer tends to only directly construct value objects which represent entities in the program's domain (such as an Employee object in a business app or an Order object in a shopping app).

Analogy 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 passenger—who only cares if it can get them to their destination. Cars present a uniform interface through their pedals, steering wheels and other controls. 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.

Advantages and disadvantages

Advantages A basic benefit of dependency injection is decreased coupling between classes and their dependencies. By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable. This also results in increased flexibility: a client may act on anything that supports the intrinsic interface the client expects. More generally, dependency injection reduces boilerplate code, since all dependency creation is handled by a singular component. Finally, dependency injection allows concurrent development. Two developers can independently develop classes that use each other, while only needing to know the interface the classes will communicate through. Plugins are often developed by third-parties that never even talk to developers of the original product.

Testing Many of dependency injection's benefits are particularly relevant to unit-testing. For example, dependency injection can be used to externalize a system's configuration details into configuration files, allowing the system to be reconfigured without recompilation. Separate configurations can be written for different situations that require different implementations of components. Similarly, because dependency injection does not require any change in code behavior, it can be applied to legacy code as a refactoring. This makes clients more independent and are easier to unit test in isolation, using stubs or mock objects, that simulate other objects not under test. This ease of testing is often the first benefit noticed when using dependency injection.

Disadvantages Critics of dependency injection argue that it:

Creates clients that demand configuration details, which can be onerous when obvious defaults are available. Makes code difficult to trace because it separates behavior from construction. Is typically implemented with reflection or dynamic programming, hindering IDE automation. Typically requires more upfront development effort. Encourages dependence on a framework.

Types of dependency injection There are several ways in which a client can receive injected services:

… excerpt ends here. Continue reading the full article.

Illustrations

Dependency injection: Dependency injection is often used alongside specialized frameworks, known as 'containers', to facilitate program composition.
Dependency injection is often used alongside specialized frameworks, known as 'containers', to facilitate program composition.
Dependency injection: PetManager gets injected into PetController and PetRepository gets injected into PetManager
PetManager gets injected into PetController and PetRepository gets injected into PetManager

Worked examples

Example 1 — a first encounter with Dependency injection

Start with the simplest possible case. Write down what Dependency injection claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Dependency injection before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Dependency injection ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Dependency injection

In research
Dependency injection appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Dependency injection in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Dependency injection is common in secondary-school and first-year university syllabi. It links to neighbouring topics Component-based software engineering, Software architecture, Software design patterns, so understanding it makes those chapters shorter.
In everyday life
Look for Dependency injection outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Dependency injection” →

How to study Dependency injection in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Dependency injection means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Dependency injection out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Dependency injection in simple terms?

In software engineering, dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally. Dependency injection aims to separate the concerns of constructing objects and using them, leading to…

Why does Dependency injection matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Dependency injection?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Dependency injection.

Tags

  • Component-based software engineering
  • Software architecture
  • Software design patterns

Keep exploring