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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With