Dagger & Android Thoughts: Dependency Injection in Android

Manuel Vivo
Mar 28, 2018 · 5 min read

Who is This Article For?

Benefits of Dagger & Android

Disclaimer

When Should I Use It?

Potential drawbacks for a large app

Common Use Case

Dagger & Android Graph
Custom solution Graph

Dagger & Android Generated Code

AndroidInjection.inject(this)

1. What is AndroidInjection.inject doing?

public static void inject(Activity activity) {
checkNotNull(activity, "activity");
Application application = activity.getApplication();
// GET THE APPLICATION OBJECT. IF IT IS NOT INSTANCE OF
// HASACTIVITYINJECTOR THEN THROW AN ERROR

if (!(application instanceof HasActivityInjector)) {
throw new RuntimeException(
String.format(
"%s does not implement %s",
application.getClass().getCanonicalName(),
HasActivityInjector.class.getCanonicalName()));
}
// GET THE ANDROID INJECTOR THAT ATTACHES SUBCOMPONENT AND ACTIVITY
AndroidInjector<Activity> activityInjector =
((HasActivityInjector) application).activityInjector();
checkNotNull(activityInjector, "%s.activityInjector() returned null", application.getClass());
// INJECT IT
activityInjector.inject(activity);
}

2. How does it know which Subcomponent Builder to use?

@Module
abstract class ActivityBuilder {

@Binds
@IntoMap
@ActivityKey(MainActivity::class)
abstract fun bindMainActivity(builder:MainSubcomponent.Builder):
AndroidInjector.Factory<out Activity>

}
private Map<Class<? extends Activity>, Provider<AndroidInjector.Factory<? extends Activity>>>
getMapOfClassOfAndProviderOfFactoryOf() {
return MapBuilder
.<Class<? extends Activity>, Provider<AndroidInjector.Factory<? extends Activity>>>
newMapBuilder(1)
.put(MainActivity.class, (Provider) mainSubcomponentBuilderProvider)
.build();
}

3. Inject the Builder to the class

Conclusion


Capital One Tech

The low down on our high tech from the engineering experts at Capital One. Learn about the solutions, ideas and stories driving our tech transformation.

Manuel Vivo

Written by

Android DevRel @ Google

Capital One Tech

The low down on our high tech from the engineering experts at Capital One. Learn about the solutions, ideas and stories driving our tech transformation.