Skip to content Skip to sidebar Skip to footer

Dagger2 Optimal Way To Inject Dependencies From Two Different Classes

After searching and trying too many things i'm stuck in some what seems like an easy problem. Below is my module which is reponsible for injecting retrofit. @Module public class Ne

Solution 1:

Please decide on whether you want to use field injection or constructor injection, and hopefully choose constructor injection.

publicclassAppUtils {
  privateContextcontext;

  @Inject// field injection?AppPreferencespreferences;

  @Inject// constructor injection?publicAppUtils(@ActivityContext Context context)
  {
    // ...
  }
}

Dagger won't inject your fields if you use constructor injection and you should not call it yourself afterwards either. Your component should really not contain all those methods to inject your presenter etc.

If you need something, put it in the constructor.

publicclassAppUtils {
  privateContextcontext;
  privateAppPreferencespreferences;

  @Inject// constructor injection!publicAppUtils(@ActivityContext Context context, AppPreferences preferences)
  {
    // ...
  }
}

The same applies for MyPresenterImpl. If you depend on something, put it in the constructor, mark the constructor with @Inject, and Dagger will create the object for you with all the dependencies provided.

Your components should only contain .inject(..) method for Android framework types (Activities, Fragments, ...) and nothing else.

I also wrote an article recently with some general concepts about the use of Dagger.

Solution 2:

my suggestion: create context module:

@ModulepublicclassContextModule
{
    Context context;

    publicContextModule(Context context) {
        this.context = context;
    }

    @Provides@AppScope
    Context context() {
        return context;
    }
}

create SharedPreferences module

@Module
public class SharedPreferencesModule
{

    @Provides@AppScope
    AppSharedPreferences provideAppSharedPreferences(Context context) {
        returnnewAppSharedPreferences(context.getSharedPreferences("App",Context.MODE_PRIVATE));
    }
}

same way You can create more modules if you need to (for example for AppUtils)

instead of creating separate component for network, create one for your app

@Component( modules = {ContextModule.class, NetworkingModule.class, SharedPreferencesModule})
publicinterfaceAppComponent {...

Post a Comment for "Dagger2 Optimal Way To Inject Dependencies From Two Different Classes"