Annotation Type AssistedInject


  • @Documented
    @Retention(RUNTIME)
    @Target(CONSTRUCTOR)
    public @interface AssistedInject
    Annotates the constuctor of a type that will be created via assisted injection.

    Note that an assisted injection type cannot be scoped. In addition, assisted injection requires the use of a factory annotated with AssistedFactory (see the example below).

    Example usage:

    Suppose we have a type, DataService, that has two dependencies: DataFetcher and Config. When creating DataService, we would like to pass in an instance of Config manually rather than having Dagger create it for us. This can be done using assisted injection.

    To start, we annotate the DataService constructor with AssistedInject and we annotate the Config parameter with Assisted, as shown below:

    
       final class DataService {
         private final DataFetcher dataFetcher;
         private final Config config;
    
         @AssistedInject
         DataService(DataFetcher dataFetcher, @Assisted Config config) {
           this.dataFetcher = dataFetcher;
           this.config = config;
         }
       }
     

    Next, we define a factory for the assisted type, DataService, and annotate it with AssistedFactory. The factory must contain a single abstract, non-default method which takes in all of the assisted parameters (in order) and returns the assisted type.

    
       @AssistedFactory
       interface DataServiceFactory {
         DataService create(Config config);
       }
     

    Dagger will generate an implementation of the factory and bind it to the factory type. The factory can then be used to create an instance of the assisted type:

    
       class MyApplication {
         @Inject DataServiceFactory dataServiceFactory;
    
         dataService = dataServiceFactory.create(new Config(...));
       }