【发布时间】:2018-08-08 09:41:12
【问题描述】:
我是 Dagger 新手,使用它时遇到问题。
我想要开发的是使用 RxAndroidBle 并通过 Dagger 对其进行初始化以提供上下文。
所以我研究了它是如何实现的,我写了一些代码,它似乎对我有用,但根本不起作用。
以下是我的代码。
AppComponent.kt
@Singleton
@Component(modules = [
AppModule::class,
BluetoothModule::class,
AndroidInjectionModule::class])
interface AppComponent : AndroidInjector<BluetoothController> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(app: Application): Builder
fun build(): AppComponent
}
}
AppModule.kt
@Module
class AppModule {
@Provides
@Named("appContext")
@Singleton
fun provideContext(application: Application): Context =
application.applicationContext
}
蓝牙模块.kt
@Module
class BluetoothModule {
@Provides
@Named("rxBleClient")
@Singleton
fun provideRxBleClient(@Named("appContext") context: Context):RxBleClient =
RxBleClient.create(context)
}
BluetoothController.kt 用于由 DaggerApplication 注入。
class BluetoothController : DaggerApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.builder().application(this).build()
}
}
我已插入 安卓:名称“.BluetoothController” 到 AndroidManifest.xml
这就是我将如何使用它。
@field:[Inject Named("rxBleClient")]
lateinit var rxBleClient: RxBleClient
但总是出现错误提示:lateinit 属性上下文尚未初始化
我错过了什么?谁能帮帮我?
提前致谢。
【问题讨论】: