Dependency injection explained

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.[1] [2] 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.[3] Dependency injection makes implicit dependencies explicit and helps solve the following problems:[4]

Dependency injection is often used to keep code in-line with the dependency inversion principle.[5] [6]

In statically typed languages using dependency injection means 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.[7]

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).[8]

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.[9]

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 when 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 represents entities in the program's domain (such as an Employee object in a business app or an Order object in a shopping app).[10] [11] [12] [13]

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 driver—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.[14] [15]

By removing a client's knowledge of how its dependencies are implemented, programs become more reusable, testable and maintainable.[16]

This also results in increased flexibility: a client may act on anything that supports the intrinsic interface the client expects.[17]

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.[18]

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.[19]

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.[20]

Disadvantages

Critics of dependency injection argue that it:

Types of dependency injection

There are three main ways in which a client can receive injected services:[26]

In some frameworks, clients do not need to actively accept dependency injection at all. In Java, for example, reflection can make private attributes public when testing and inject services directly.[27]

Without dependency injection

In the following Java example, the Client class contains a Service member variable initialized in the constructor. The client directly constructs and controls which service it uses, creating a hard-coded dependency.

public class Client

Constructor injection

The most common form of dependency injection is for a class to request its dependencies through its constructor. This ensures the client is always in a valid state, since it cannot be instantiated without its necessary dependencies. public class Client

Setter injection

By accepting dependencies through a setter method, rather than a constructor, clients can allow injectors to manipulate their dependencies at any time. This offers flexibility, but makes it difficult to ensure that all dependencies are injected and valid before the client is used.

public class Client

Interface injection

With interface injection, dependencies are completely ignorant of their clients, yet still send and receive references to new clients.

In this way, the dependencies become injectors. The key is that the injecting method is provided through an interface.

An assembler is still needed to introduce the client and its dependencies. The assembler takes a reference to the client, casts it to the setter interface that sets that dependency, and passes it to that dependency object which in turn passes a reference to itself back to the client.

For interface injection to have value, the dependency must do something in addition to simply passing back a reference to itself. This could be acting as a factory or sub-assembler to resolve other dependencies, thus abstracting some details from the main assembler. It could be reference-counting so that the dependency knows how many clients are using it. If the dependency maintains a collection of clients, it could later inject them all with a different instance of itself.

public interface ServiceSetter

public class Client implements ServiceSetter

public class ServiceInjector

public class ExampleService implements Service

public class AnotherExampleService implements Service

Assembly

The simplest way of implementing dependency injection is to manually arrange services and clients, typically done at the program's root, where execution begins.

public class Program

Manual construction may be more complex and involve builders, factories, or other construction patterns.

Frameworks

Manual dependency injection is often tedious and error-prone for larger projects, promoting the use of frameworks which automate the process. Manual dependency injection becomes a dependency injection framework once the constructing code is no longer custom to the application and is instead universal. While useful, these tools are not required in order to perform dependency injection.[28] [29]

Some frameworks, like Spring, can use external configuration files to plan program composition:

import org.springframework.beans.factory.BeanFactory;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Injector

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.[30] [31] [32] By keeping Spring-specific annotations and calls from spreading out among many classes, the system stays only loosely dependent on Spring.

Examples

AngularJS

The following example shows an AngularJS component receiving a greeting service through dependency injection.

function SomeClass(greeter)

SomeClass.prototype.doSomething = function(name)

Each AngularJS application contains a service locator responsible for the construction and look-up of dependencies.

// Provide the wiring information in a modulevar myModule = angular.module('myModule', []);

// Teach the injector how to build a greeter service. // greeter is dependent on the $window service.myModule.factory('greeter', function($window));

We can then create a new injector that provides components defined in the myModule module, including the greeter service.

var injector = angular.injector(['myModule', 'ng']);var greeter = injector.get('greeter');

To avoid the service locator antipattern, AngularJS allows declarative notation in HTML templates which delegates creating components to the injector.

function MyController($scope, greeter)

The ng-controller directive triggers the injector to create an instance of the controller and its dependencies.

C#

This sample provides an example of constructor injection in C#.using System;

namespace DependencyInjection;

// Our client will only know about this interface, not which specific gamepad it is using.interface IGamepadFunctionality

// The following services provide concrete implementations of the above interface.

class XBoxGamepad : IGamepadFunctionality

class PlaystationJoystick : IGamepadFunctionality

class SteamController : IGamepadFunctionality

// This class is the client which receives a service.class Gamepad

class Program

Go

Go does not support classes and usually dependency injection is either abstracted by a dedicated library that utilizes reflection or generics (the latter being supported since Go 1.18 [33]).[34] A simpler example without using dependency injection libraries is illustrated by the following example of an MVC web application.

First, pass the necessary dependencies to a router and then from the router to the controllers:package router

import ("database/sql" "net/http"

"example/controllers/users"

"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware"

"github.com/redis/go-redis/v9" "github.com/rs/zerolog")

type RoutingHandler struct

// connection, logger and cache initialized usually in the main functionfunc NewRouter(log *zerolog.Logger, db *sql.DB, cache *redis.Client,) (r *RoutingHandler)

func (r *RoutingHandler) SetupUsersRoutes

Then, you can access the private fields of the struct in any method that is it's pointer receiver, without violating encapsulation.package users

import ("database/sql" "net/http"

"example/models"

"github.com/go-chi/chi/v5" "github.com/redis/go-redis/v9" "github.com/rs/zerolog")

type Controller struct

func NewController(log *zerolog.Logger, db *sql.DB, cache *redis.Client) *Controller

func (uc *Controller) Get(w http.ResponseWriter, r *http.Request)

Finally you can use the database connection initialized in your main function at the data access layer:package models

import ("database/sql""time")

type (UserStorage struct

User struct)

func NewUserStorage(conn *sql.DB) *UserStorage

func (us *UserStorage) Get(name string) (user *User, err error)

See also

External links

Notes and References

  1. Web site: Seemann . Mark . Dependency Injection is Loose Coupling . 2015-07-28 . blog.ploeh.dk.
  2. Niko Schwarz, Mircea Lungu, Oscar Nierstrasz, “Seuss: Decoupling responsibilities from static methods for fine-grained configurability”, Journal of Object Technology, Volume 11, no. 1 (April 2012), pp. 3:1-23
  3. Web site: HollywoodPrinciple . 2015-07-19 . c2.com.
  4. Web site: The Dependency Injection design pattern - Problem, Solution, and Applicability . 2017-08-12 . w3sDesign.com.
  5. Web site: Erez . Guy . 2022-03-09 . Dependency Inversion vs. Dependency Injection . 2022-12-06 . Medium . en.
  6. Web site: Mathews . Sasha . 2021-03-25 . You are Simply Injecting a Dependency, Thinking that You are Following the Dependency Inversion… . 2022-12-06 . Medium . en .
  7. Web site: Spring IoC Container . 2023-05-23 . en .
  8. Web site: Fowler . Martin . Inversion of Control Containers and the Dependency Injection pattern . MartinFowler.com . 4 June 2023.
  9. Web site: I.T. . Titanium . James Shore: Dependency Injection Demystified . 2015-07-18 . www.jamesshore.com.
  10. Web site: To "new" or not to "new"… . 2015-07-18 . 2020-05-13 . https://web.archive.org/web/20200513185005/http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/ . dead .
  11. Web site: How to write testable code . 2015-07-18 . www.loosecouplings.com.
  12. Web site: Writing Clean, Testable Code . 2015-07-18 . www.ethanresnick.com.
  13. Web site: Sironi . Giorgio . When to inject: the distinction between newables and injectables - Invisible to the eye . 2015-07-18 . www.giorgiosironi.com.
  14. Web site: the urban canuk, eh: On Dependency Injection and Violating Encapsulation Concerns. 2015-07-18. www.bryancook.net.
  15. Web site: The Dependency Injection Design Pattern. 2015-07-18. msdn.microsoft.com.
  16. Web site: The Java Community Process(SM) Program - JSRs: Java Specification Requests - detail JSR# 330. 2015-07-18. jcp.org.
  17. Web site: 3.1. Dependency injection — Python 3: from None to Machine Learning. dead . https://web.archive.org/web/20200208005839/http://python.astrotech.io/design-patterns/structural/dependency-injection.html . 2020-02-08 .
  18. Web site: How Dependency Injection (DI) Works in Spring Java Application Development - DZone Java.
  19. Web site: Dependency injection and inversion of control in Python — Dependency Injector 4.36.2 documentation.
  20. Web site: How to Refactor for Dependency Injection, Part 3: Larger Applications .
  21. Web site: A quick intro to Dependency Injection: What it is, and when to use it . 18 October 2018 .
  22. Web site: Dependency Injection Professionalqa.com .
  23. Web site: What are the downsides to using Dependency Injection? . 2015-07-18 . stackoverflow.com.
  24. Web site: Dependency Injection Inversion – Clean Coder . sites.google.com . 2015-07-18 .
  25. Web site: Decoupling Your Application From Your Dependency Injection Framework . InfoQ . 2015-07-18 .
  26. Web site: Martin Fowler . Inversion of Control Containers and the Dependency Injection pattern – Forms of Dependency Injection . Martinfowler.com . 2004-01-23 . 2014-03-22 .
  27. Web site: AccessibleObject (Java Platform SE 7) . 2015-07-18 . docs.oracle.com .
  28. Web site: Dependency Injection != using a DI container . 2015-07-18 . www.loosecouplings.com .
  29. Web site: Black Sheep » DIY-DI » Print . dead . https://web.archive.org/web/20150627215638/http://blacksheep.parry.org/archives/diy-di/print . 2015-06-27 . 2015-07-18 . blacksheep.parry.org .
  30. Web site: Spring Tips: A POJO with annotations is not Plain . 2015-07-18 . https://web.archive.org/web/20150715045353/http://springtips.blogspot.com/2007/07/pojo-with-annotations-is-not-plain.html . 2015-07-15 . dead .
  31. Web site: Annotations in POJO – a boon or a curse? Techtracer . 2015-07-18 . 2007-04-07 .
  32. Book: Pro Spring Dynamic Modules for OSGi Service Platforms . APress . 2015-07-06 . 9781430216124 . 2009-02-17 .
  33. Web site: Go 1.18 Release Notes - The Go Programming Language . 2024-04-17 . go.dev . en.
  34. Web site: April 17, 2024 . Awesome Go – dependency injection . April 17, 2024 . Github.