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
andConfig
. When creatingDataService
, we would like to pass in an instance ofConfig
manually rather than having Dagger create it for us. This can be done using assisted injection.To start, we annotate the
DataService
constructor withAssistedInject
and we annotate theConfig
parameter withAssisted
, 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 withAssistedFactory
. 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(...)); }