WIPIVERSE All articles

Dependency injection

Dependency injection (DI) is a software design pattern and technique in which an object or function receives other objects or functions that it depends on, rather than creating them internally. It is a specific form of inversion of control (IoC) aimed at achieving loose coupling between classes and their dependencies.

Core Concept In traditional programming, a client class typically instantiates its own dependencies (services, repositories, configuration objects) directly, often using the new keyword or a static factory method. This creates a hard-coded coupling between the client and the specific implementation of the dependency.

Dependency injection separates the creation of a dependency from its usage. The dependency is "injected" into the client by an external entity, often referred to as an injector, container, or framework. The client only defines the interface or abstract type it requires, remaining agnostic to the concrete implementation.

Injection Methods There are three primary methods for injecting dependencies:

  1. Constructor Injection: Dependencies are provided through the client's constructor. This is generally the preferred method for mandatory dependencies, as it ensures the client is always in a valid, fully initialized state and allows dependencies to be immutable (readonly/final).
  2. Setter Injection (Property Injection): Dependencies are set via public setter methods or properties after the client is instantiated. This allows for optional dependencies or reconfiguration but can lead to temporal coupling (the object may exist in an incomplete state before injection).
  3. Interface Injection: The dependency provides an injector method that injects the dependency into any client passed to it, provided the client implements a specific interface. This is less common in modern mainstream frameworks.

Roles

  • Service (Dependency): The object containing the functionality required by the client.
  • Client (Consumer): The object that depends on the service.
  • Interface (Contract): The abstraction defining how the client uses the service, decoupling the client from the concrete implementation.
  • Injector (Container/Framework): The external mechanism responsible for instantiating services and injecting them into clients.

Benefits

  • Loose Coupling: Clients depend on abstractions, not concrete implementations, facilitating the substitution of implementations (e.g., swapping a database repository for an in-memory one).
  • Testability: Dependencies can be easily replaced with mock objects, stubs, or fakes during unit testing, allowing the client to be tested in isolation.
  • Maintainability: Separation of concerns is enforced; configuration and wiring logic are centralized in the composition root (often a DI container), rather than scattered throughout the codebase.
  • Reusability: Classes become more reusable in different contexts because they do not dictate their own dependencies.

Drawbacks and Complexity

  • Complexity: Introduces indirection, which can make code flow harder to trace for developers unfamiliar with the pattern.
  • Configuration Overhead: Requires explicit registration and configuration of dependencies (often via XML, annotations, attributes, or fluent APIs), which can become verbose in large applications.
  • Runtime Errors: Misconfiguration (e.g., missing bindings, circular dependencies) often results in runtime startup failures rather than compile-time errors.
  • Performance: Reflection-based container scanning and resolution can introduce minor startup latency, though compile-time DI generators (source generators) mitigate this.

Dependency Injection Containers (Frameworks) While DI can be implemented manually ("Pure DI" or "Poor Man's DI") by wiring objects in a composition root, most production applications use a DI Container (Inversion of Control Container) to automate the resolution and lifecycle management of dependencies. Common examples include:

  • Java: Spring Framework, Google Guice, Dagger, Micronaut, Quarkus.
  • .NET: Built-in Microsoft.Extensions.DependencyInjection, Autofac, Ninject, DryIoc.
  • Python: dependency-injector, FastAPI's built-in DI, Pinject.
  • JavaScript/TypeScript: InversifyJS, NestJS DI, Angular DI.
  • Go: Uber Dig, Wire (compile-time), Google Wire.
  • PHP: Symfony DependencyInjection, PHP-DI, Laravel Service Container.

Lifecycles / Scopes Containers manage the lifecycle of instantiated services. Common scopes include:

  • Transient: A new instance is created every time the service is requested.
  • Scoped: A single instance is created per logical scope (typically per HTTP request in web applications).
  • Singleton: A single instance is created and shared for the lifetime of the container/application.

Relationship to Other Patterns

  • Inversion of Control (IoC): DI is a concrete implementation of the broader IoC principle. IoC states that control of object creation and lifecycle is inverted from the library/code to the framework/container.
  • Service Locator: Often considered an anti-pattern in DI contexts. The client requests dependencies from a central registry (locator) rather than having them pushed in. This hides dependencies inside the class implementation rather than exposing them in the constructor signature.
  • Factory Pattern: Factories can be used within DI to create dependencies that require runtime parameters or complex initialization logic that the container cannot handle automatically.
Browse

More topics to explore

    Browse all articles