Using Dagger for dependency injection on constructors

What Jake's post says is perfectly true. That said, we (some of the Google folk who work with Guice and Dagger) are working on an alternative version of "assisted injection" or automatic-factory generation which should be usable by Guice or Dagger or stand-alone - that is, it will generate factory class source code for you. These factory classes will (if appropriate) be injectable as any standard JSR-330 class would. But it is not yet released.

Pending a solution like this, Jake Wharton's approach is advisable.


What you are talking about is known as assisted injection and is not currently supported by Dagger in any automatic fashion.

You can work around this with the factory pattern:

class AFactory {
  @Inject DebugLogger debuggLogger;

  public A create(int amount, int frequency) {
    return new A(debuggLogger, amount);
  }
}

Now you can inject this factory and use it to create instances of A:

class B {
  @Inject AFactory aFactory;

  //...
}

and when you need to create an A with your 'amount' and 'frequency' you use the factory.

A a = aFactory.create(amount, frequency);

This allows for A to have final instances of the logger, amount, and frequency fields while still using injection to provide the logger instance.

Guice has an assisted injection plugin which essentially automates the creation of these factories for you. There have been discussion on the Dagger mailing list about the appropriate way for them to be added but nothing has been decided upon as of this writing.