我正在尝试使用Dagger 2注入Context。我在此网站上看到了许多与此相关的其他问题,但仍然无法解决问题。
AppComponent.kt:
@Singleton
@Component(
modules = [
AppModule::class
]
)
interface AppComponent {
fun context(): Context
fun inject(context: Context)
}
AppModule.kt:
@Module
class AppModule(private val context: Context) {
@Provides
@Singleton
fun providesApplicationContext(): Context = context
}
MainApp.kt:
class MainApp : Application() {
lateinit var appComponent: AppComponent
override fun onCreate() {
super.onCreate()
appComponent = initDagger()
appComponent.inject(this)
}
private fun initDagger() = DaggerAppComponent.builder()
.appModule(AppModule(this))
.build()
}
Manager.kt :(我要在其中注入上下文的类)
class Manager {
@Inject
lateinit var context: Context
fun foo() {
context.resources
}
}
但是,当从任何地方调用context.resources
时,例如在Manager().foo()
的onCreate()
函数中,当我在MainActivity
处出现以下错误:
kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized
如何解决?为什么Dagger不注入Context
?
尝试使用constructor
注射
class Manager @Inject constructor(val context: Context) {
fun foo() {
context.resources
}
}