首页 > 解决方案 > Dagger 2.26 字段注入应用程序失败

问题描述

当我尝试使用lateinit 属性注入应用程序崩溃时...尚未初始化异常。我知道我必须将我的应用程序注入图表,但我没有成功。做这个的最好方式是什么?

class App : Application() {

    @Inject
    lateinit var localeManager: Lazy<LocaleManager>

    val appComponent: AppComponent by lazy {
        DaggerAppComponent.factory().create(applicationContext)
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(localeManager.get().setLocale(base))
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        localeManager.get().setLocale(this)
    }
}

@Singleton
@Component(modules = [NetworkModule::class, AppSubcomponents::class])
interface AppComponent {
    @Component.Factory
    interface Factory {
        fun create(@BindsInstance context: Context): AppComponent
    }

    fun registrationComponent(): RegistrationComponent.Factory
    fun lobbyComponent(): PropertyComponent.Factory
    fun supplierComponent(): SupplierComponent.Factory
    fun notificationComponent(): NotificationComponent.Factory
    fun serviceComponent(): ServiceComponent.Factory
    fun settingsComponent() : SettingsComponent.Factory
    fun cardComponent() : CardComponent.Factory

    fun inject(activity: MainActivity)

}

class LocaleManager @Inject constructor(val storage: UserStorage) {
   //some code 
}

标签: androidkotlindagger

解决方案


推荐阅读