Better Dagger dependency injection based on build type and flavor?
Little complicated but here's how I did it:
Create an interface MainComponent and keep it in src/main, this should contain anything that is not flavor specific
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
public interface FlavorComponent extends MainComponent {
//flavor specific injection stuff similar to SourceComponent
}
Within Debug/Beta/Release create the actual component and extend the FlavorComponent (giving you all the flavor specific niceties).
@Singleton
@Component(modules = {ApplicationModule.class, FlavorModule.class,
BetaApplicationModule.class, AnotherModuleJustBecause.class})
public interface ApplicationComponent extends FlavorComponent {
void inject(NYTApplication a);
}
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.
Also include a ComponentFactory within Debug/Beta/Release returning the common Flavor Component Interface
public class ComponentFactory {
public static final FlavorComponent getComponent(Application context) {
return DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(context))
.build();
}
and finally from your Application class call:
ComponentFactory.getComponent(this).inject(this);
The component factory will return the Build Type Component which will extend the Flavor's Component.