Flavoring your Dagger

Mike Nakhimovich Blocked Unblock Follow Following Oct 13, 2015

As an android app grows larger, Dependency Injection becomes a valuable patter to both organize your codebase into modules and to destruct boilerplate. With ProGuard support and performance improvements, Dagger 2 is the defacto Android standard for dependency injection. Here’s a simple way to setup Dagger 2 which will allow the addition of any combinations of modules split across multiple build variants.

First, Create an interface MainComponent and keep it in src/main, this should contain anything that is not flavor specific, don’t annotate this interface with anything

public interface MainComponent {

void inject(MyApplication o);



void inject(BusinessObject o);

Foo getFoo();



Activitycomponent plusActivityComponent(ActivityModule activityModule);

}

Within each flavor create an interface that inherits from the above one again not adding any annotations

public interface FlavorComponent extends MainComponent {

//flavor specific injection stuff similar to SourceComponent

}

Within Debug/Beta/Release create the actual component and extend the FlavorComponent(which will be from whatever flavor is currently active).

Notice that you can also include a flavor specific FlavorModule that can be different in each flavor or not include it in Release while including it in Beta.

@Singleton

@Component(modules = {ApplicationModule.class, FlavorModule.class,

BetaApplicationModule.class, AnotherModuleJustBecause.class})

public interface ApplicationComponent extends FlavorComponent {

void inject(NYTApplication a);



}

The FlavorModule will live within the flavor source tree while some modules may be coming from the main source and others from the build types sources.

Next add a ComponentFactory within Debug/Beta/Release returning the common FlavorComponent Interface

public class ComponentFactory {

public static final FlavorComponent create(Application context) {

return DaggerApplicationComponent.builder()

.applicationModule(new ApplicationModule(context))

.build();

}

Finally from your Application class call:

ComponentFactory.create();

The result is a reference to a Component that contains both flavor specific and build type objects