Dagger 2 未注入,lateinit 属性 未初始化
Dagger 2 not injecting, lateinit property not initialized
我正在尝试使用 Dagger 2 注入上下文。我在这个网站上看到了很多其他与此相关的问题,但问题仍然没有解决。
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我要注入上下文的地方)
class Manager {
@Inject
lateinit var context: Context
fun foo() {
context.resources
}
}
但是,当从任何地方调用 Manager().foo()
时,我在 context.resources
收到以下错误,例如 MainActivity
的 onCreate()
函数:
kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized
如何解决这个问题?为什么 Dagger 没有注入 Context
?
尝试使用constructor
注入
class Manager @Inject constructor(val context: Context) {
fun foo() {
context.resources
}
}
然后在您的 Activity/Fragment
中使用 manager
,如下所示:
@Inject lateinit var manager: Manager
我正在尝试使用 Dagger 2 注入上下文。我在这个网站上看到了很多其他与此相关的问题,但问题仍然没有解决。
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我要注入上下文的地方)
class Manager {
@Inject
lateinit var context: Context
fun foo() {
context.resources
}
}
但是,当从任何地方调用 Manager().foo()
时,我在 context.resources
收到以下错误,例如 MainActivity
的 onCreate()
函数:
kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized
如何解决这个问题?为什么 Dagger 没有注入 Context
?
尝试使用constructor
注入
class Manager @Inject constructor(val context: Context) {
fun foo() {
context.resources
}
}
然后在您的 Activity/Fragment
中使用 manager
,如下所示:
@Inject lateinit var manager: Manager