java - Store Dagger component in a static field -


i´m new in dagger2 , of time i´ve seen people creating appcomponent in extended application class. time need appcomponent you´ll request through application class.

public class app extends application {  private appcomponent mappcomponent;  @override public void oncreate() {     super.oncreate();      mappcomponent = daggerappcomponent.builder()             .applicationmodule(new applicationmodule(this))             .build(); }  public appcomponent getappcomponent() {     return mappcomponent; }  @visiblefortesting public void setappcomponent(appcomponent appcomponent) {     mappcomponent = appcomponent; } } 

i´ve seen people using componentfactory

public class componentfactory {  public static final appcomponent getcomponent(application context) {         return daggerapplicationcomponent.builder()                 .applicationmodule(new applicationmodule(context))                 .build();     } 

which pros , cons storing appcomponent in application class?

is better create through factory each time need it?

will problem if keep in static field component instead of building each time?

building component each time can (depending on size of component) wasteful, more importantly, @scope annotations use not share same instance if recreate component each time. storing component in application class common approach provides canonical place retrieve component across app. static field can tricky when consider lifecycle of app (especially testing) , considered anti-pattern. lot of same benefits keeping component in application class since can correctly assume android framework create 1 application instance long app alive. if there's 1 application , creates 1 component, ensure singularity , can control visibility component.


Comments