Skip to content

Dependency Injection

Pierre T. edited this page Jan 12, 2015 · 2 revisions

DI (Dependency Injection) is a design pattern which allows amongst other things to respect the "Single Responsibility Principle" (SRP). This principle says that a module should have only one responsibility and one reason to change. To do its job, the module often needs dependencies. To respect the SRP, the module can't do its job and handle external dependencies. Moreover, the code would be confuse. That's why DI is used.

We can see DI like a pattern allowing IOC, because it delegate a part of the control to lower layer allowing to focus on business or functional development.

Different terms are used when we talk about DI:

  • Injection point: Mechanism which define in a class the point where the injection should be done. When identified, this injection point can add metadata given more information on which dependency should be injected. There is several ways of defining injection points:
  • A priori, inside the module to inject: by adding the standard annotation @javax.inject (from the JSR 330).
  • A posteriori, outside the module to inject: defining the injection points in a non-typed file. For instance, the XML format for Spring Core.
  • Binding definition: a binding definition is the definition of a link between one or more injection points and the injection of dependency to inject (or a provider of the instance). This binding definition is defined by a a pair of [Type, Qualifier], the type being the name of the class or the interface to inject and the qualifier being a unique (and optional) string. This pair is sometime called a key. It is a typed binding definition. It exists two types of typed binding definition:
  • explicit typed binding definition, where the type is explicitly given at the binding definition.
  • implicit typed binding definition, where the final type is not clearly defined at the binding definition, but guessed by the injection engine with a super type or another hint given at the definition.
  • A qualifier alone is an untyped binding.
  • The binding scope defines the strategy to create instance. For example, a singleton scope on a binding definition will use only one instance for all the injections. The "no scope" scope (by default in Nuun) will provide a new instance each time. Other scopes exist: "request", "session", etc.

Content

Clone this wiki locally