Currently, in order to get an instance, for example, Picasso in action, I need to add an add method to the AppComponent. How to avoid adding an injection method, because I have many fragments and views where it should be introduced:
AppComponent.class:
@ForApplication @Singleton @Component( modules = {AppModule.class,OkHttpClientModule.class,NetworkApiModule.class,NetworkAuthModule.class}) public interface AppComponent { void inject(Fragment1 obj); void inject(Fragment2 obj); void inject(Fragment3 obj); void inject(Fragment4 obj); void inject(Fragment5 obj); void inject(Fragment6 obj); ... }
Fragment1.class
public class Fragment1 extends Fragment { @Inject Picasso mPicasso; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyApplication.getComponent(getContext()).inject(this); } }
My classes are:
AppModule.class:
@Module public class AppModule { private MyApplication mApplication; public AppModule(@NonNull MyApplication mApplication) { this.mApplication = mApplication; } @Provides @NonNull @Singleton public Application provideApplication() { return mApplication; } @Provides @ForApplication Context provideContext(){ return mApplication; } @Provides @Singleton Picasso providesPicasso(@ForApplication Context context) { return new Picasso.Builder(context).build(); } }
ForApplication.class:
@Scope @Retention(RUNTIME) public @interface ForApplication { }
Myapplication.class
public class MyApplicationextends Application { static Context mContext; private AppComponent component; @Override public void onCreate() { super.onCreate(); mContext = this; setupComponent(); } private void setupComponent() { component = DaggerAppComponent.builder().appModule(new AppModule(this)).build(); component.inject(this); } public AppComponent getComponent() { if (component==null) setupComponent(); return component; } public static AppComponent getComponent(Context context) { return ((MyApplication) context.getApplicationContext()).getComponent(); }
UPDATE
I also want to add adapters for fragments, and if I add BaseFragment to the base, then BaseFragment will have all adapters for all child fragments
java android dependency-injection dagger-2
NickUnuchek
source share