Skip to content

Modules & Bindings

Stéphane Nicolas edited this page May 7, 2016 · 23 revisions

Modules define bindings.

The class toothpick.config.Module defines a small DSL to conveniently express bindings, and bindings can be expressed in various ways :

class SimpleModule extends Module {
  SimpleModule() {
    bind(IFoo.class).to(Foo.class); // case 1
    bind(IFoo.class).to(new Foo()); // case 2
    bind(IFoo.class).toProvider(FooProvider.class); // case 3
    bind(IFoo.class).toProvider(new FooProvider()); // case 4
    bind(Foo.class); // case 5
  }
}

The various binding modes are :

  • case 1: Every @Inject IFoo will be assigned a new instance of Foo.
  • case 2: Every @Inject IFoo will be assigned the same instance of Foo. The instance defined in the module.
  • case 3: Every @Inject IFoo will be assigned a new instance of Foo produced by a new instance of FooProvider.
  • case 4: Every @Inject IFoo will be assigned a new instance of Foo produced by the same instance of FooProvider. The instance defined in the module.
  • case 5 : Every @Inject Foo will be assigned a new instance of Foo.

Bindings, instance creations and injections

In the example above, in the cases 1, 3 and 5, ToothPick is responsible for creating the instances during injection. Whereas in cases 2 and 4, the developer herself is creating the instances of Foo, either directly or via a provider that she defines.

A good rule to remember is :

As soon as ToothPick creates an object, it will be injected.

which also implies that :

As soon as a developer creates an object with ToothPick, the developer has to take care of injecting this object dependencies.

This means that if we define the class :

class Foo {
  @Inject Scope s;
}

In the cases 1, 3 and 5, all instances of Foo that are created during injection by ToothPick will themselves be injected. All injected methods and fields will be called/assigned and their annotated constructor or the default constructor will be used to create the instances of Foo.

In the case 2 and 4, the developer will have to assign the field s to a scope, the developer can do it manually or by asking ToothPick to do it : ToothPick.inject( foo, s ).

Clone this wiki locally