OS 006: Dependency Injection with Guice

OS-006 Dependency Injection with Guice

Date: 2018-02-20

Status

Implemented

Context

OS 006 head

The modules provided as tangly open source components are used in more complex applications.

These applications often use dependency injection frameworks to construct and initialize their instances. Dependency injection is a technique in which an object receives other objects that it depends on, called dependencies.

Typically, the receiving object is called a client. The passed-in injected object is called a service. The code that passes the service to the client is called the injector.

Instead of the client specifying that service it will use, the injector tells the client what service should be used. The injection refers to the passing of a dependency into the client that uses it.

Decision

Guice is selected as a dependency injection framework.

  1. Guice is one of the industrial standards with Dagger and Sprint DI.

  2. Guice supports JDK standard @inject annotation used in other dependency frameworks.

  3. Guice supports the definition of modules to describe dependencies. The modules are also used as a documentation mechanism.

Care will be taken to allow users to use a different dependency injection framework.

Consequences

  • A dependency injection module shall be provided for each relevant module.

Honestly, we are not providing the module for our modules. Our applications are quite simple and use a handful of services. This solution of a static repository works fine. This approach is much simpler to reason about, much faster to start, much easier to debug and to maintain.

public final class Services {
    private Services() {}
    public static LoginService getLoginService() {}
    public static ThatService getThatService() {}
}

Conventions

  1. Constructor injection is the preferred mechanism. In the long term, it should be the only approach.

  2. Please avoid field injection as an injection approach.