Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger 2.15 - How to inject a dependency in Application class

I am unable to inject a depency in DaggerApplication class

The relevant classes are as follows

Application

class App : DaggerApplication() {

@Inject lateinit var mSomeClass : SomeClass // This is always NULL

override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
    return DaggerAppComponent.builder().application(this).build()
 }


override fun onCreate() {
    super.onCreate()

    mSomeClass.initialize()  // mSomeClass is NULL
}

Component:

 @Singleton
 @Component(modules = [
    AndroidSupportInjectionModule::class,
    AppModule::class,
    ViewModelFactoryModule::class,
    BuildersModule::class
  ])
interface AppComponent : AndroidInjector<DaggerApplication> {

@Component.Builder
interface Builder {

    @BindsInstance
    fun application(application: Application): Builder

    fun build(): AppComponent
    }
}

AppModule class:

    @Module
    class AppModule {

    @Provides
    fun provideSomeClass(context: Context) = SomeClass(context = context)
}

Not sure what is missing.

like image 343
silent_control Avatar asked May 29 '18 15:05

silent_control


1 Answers

I experienced the same problem and figure out that we can not call inject(this) in Application class when using DaggerApplication in AppComponent. Because of this, we can not inject anything I think.

So in the AppComponent you have to specify your Application Class instead of typing DaggerApplication

Your AppComponent should be like this

@Singleton
@Component(modules = {AndroidSupportInjectionModule.class, AppModule.class})
public interface AppComponent extends AndroidInjector<MyApplication> {

    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);
        AppComponent build();

    }

}

And your Application class

    public class MyApplication extends DaggerApplication {

        @Inject
        SomeClass mSomeClass;

        @Override
        public void onCreate() {
            super.onCreate();
            mSomeClass.initialize();
        }

        @Override
        protected AndroidInjector<MyApplication> applicationInjector() {
            AppComponent appComponent = DaggerAppComponent.builder().application(this).build();
            appComponent.inject(this);
            return appComponent;
        }
        }

Now you can inject in Application class.

Little note: If I said something wrong please correct me, I am not expert about Dagger :)

like image 178
ysfcyln Avatar answered Oct 22 '22 04:10

ysfcyln