Dependency injection in Android activity with Dagger 2 - Tuong-Nguyen/PreparationEduLog GitHub Wiki
Introduction
Android components (activities, fragments, ...) are instantiated by the Android framework which makes it difficult to use dependency injection on them. By doing a little setup, Dagger with provided classes help to simplifies the dependency injection into Android components.
Setup
Dependencies
- Add Dagger dependencies to
app.gradle
compile 'com.google.dagger:dagger:2.10'
annotationProcessor 'com.google.dagger:dagger-compiler:2.10'
- In order to use classes from
dagger.android
package, likeDaggerActivity
, add the dependencies
compile 'com.google.dagger:dagger-android:2.10'
annotationProcessor 'com.google.dagger:dagger-android-processor:2.10'
- Use support libraries with Dagger 2
compile 'com.google.dagger:dagger-android-support:2.10'
Dagger subcomponent
Subcomponent interface
@Subcomponent
public interface IMainActivitySubcomponent extends AndroidInjector<MainActivity> {
@Subcomponent.Builder
abstract class Builder extends AndroidInjector.Builder<MainActivity> {}
}
- Represents a Dagger subcomponent which is able to inherit bindings from any parent subcomponent/component
- Extends AndroidInjector to perform member injection on a concrete Android component type
- Annotate with @Subcomponent
Module to add subcomponent
@Module(subcomponents = {IMainActivitySubcomponent.class})
public abstract class ActivityModule {
@Binds
@IntoMap
@ActivityKey(MainActivity.class)
abstract AndroidInjector.Factory<? extends Activity> bindYourActivityInjectorFactory(IMainActivitySubcomponent.Builder builder);
}
- Annotate with @Module
- Help the sub components in
subcomponent
parameter are available - Binds the builder of the subcomponent to
AndroidInjector.Factory
Application
ApplicationComponent interface
@Component(modules = {ActivityModule.class, AndroidInjectionModule.class})
public interface ApplicationComponent {
void inject(MyApplication application);
}
- Responsible for injecting the Application class
- @Component annotation with the
modules
parameter to specify which modules are used to create implementation of the componentActivityModule
make use of subcomponent to inject activitiesAndroidInjectionModule
is needed to ensure the binding of Android component (Activity, Fragment, ...)