javaguicedaggergwt-gindagger-2

Can I use some kind of assisted Inject with Dagger?


With Google Guice or Gin I can specify parameter with are not controlled by the dependency injection framework:

class SomeEditor {


  @Inject
  public SomeEditor(SomeClassA a, @Assisted("stage") SomeClassB b) {
  }

}

The assisted parameter stage is specified at the time an instance of SomeEditor is created.

The instance of SomeClassA is taken from the object graph and the instance of SomeClassB is taken from the caller at runtime.

Is there a similar way of doing this in Dagger?


Solution

  • UPDATE: As of Dagger 2.31 from January 2021, Dagger now natively supports assisted injection, which is recommended over the Square and Auto options. (Those other options still work, but may require extra setup compared to the native option.)

    class SomeEditor {
      @AssistedInject public SomeEditor(
          SomeClassA a, @Assisted SomeClassB b) {
        // ...
      }
    }
    
    @AssistedFactory interface SomeEditorFactory {
      SomeEditor create(SomeClassB b);
    }
    

    (original answer)

    Because factories are a separate type of boilerplate to optimize away (see mailing list discussion here), Dagger leaves it to a sister project, AutoFactory. This provides the "assisted injection" functionality Guice offers via FactoryModuleBuilder, but with some extra benefits:

    Example, pulled from AutoFactory's README, which will produce a SomeClassFactory with providedDepA in an @Inject-annotated constructor and depB in a create method:

    @AutoFactory
    final class SomeClass {
      private final String providedDepA;
      private final String depB;
    
      SomeClass(@Provided @AQualifier String providedDepA, String depB) {
        this.providedDepA = providedDepA;
        this.depB = depB;
      }
    
      // …
    }