gpt4 book ai didi

android - Dagger 2的麻烦

转载 作者:行者123 更新时间:2023-11-29 18:25:40 25 4
gpt4 key购买 nike

您好,我在我的项目中使用此配置的 dagger 2。

这是我的 SellerHubApplication.kt

class SellerHubApplication : Application(), HasAndroidInjector {

@Inject
lateinit var activityDispatchingAndroidInjector: AndroidInjector<Any>

override fun androidInjector(): AndroidInjector<Any> = activityDispatchingAndroidInjector

override fun onCreate() {
super.onCreate()

DaggerAppComponent.builder()
.application(this)
.build()
.inject(this)

Fresco.initialize(applicationContext)
}

这是我的 AppComponent.kt

@Singleton
@Component(modules = [AndroidInjectionModule::class, ActivityBuilder::class, AppModule::class])
interface AppComponent {

@Component.Builder
interface Builder {
@BindsInstance
fun application(app: Application): Builder

fun build(): AppComponent
}

fun inject(app: SellerHubApplication)

}

运行应用程序后,我收到此错误“错误:[Dagger/MissingBinding] dagger.android.AndroidInjector cannot be provided without an @Provides-annotated method.”

如果我将“fun inject(app: SellerHubApplication)”更改为“fun inject(app: Application)”,应用程序运行但它显示“activityDispatchingAndroidInjector 尚未初始化”。请帮我解决这个问题。

最佳答案

尝试这样做:

应用组件:

@Singleton
@Component(modules = [AndroidInjectionModule::class, ActivityBuilder::class, AppModule::class, FragmentBuilder::class,])
interface AppComponent : AndroidInjector< SellerHubApplication > {

@Component.Builder
interface Builder {
@BindsInstance
fun application(application: SellerHubApplication): Builder

fun applicationModule(applicationModule: AppModule): Builder
fun build(): AppComponent
}
}

应用:

class SellerHubApplication : Application(), HasActivityInjector, HasSupportFragmentInjector {

@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>

@Inject
lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>


companion object {
lateinit var applicationComponent: AppComponent
private set
}


override fun onCreate() {
super.onCreate()

init()
}

override fun activityInjector(): AndroidInjector<Activity> {
return dispatchingAndroidInjector
}

override fun supportFragmentInjector(): AndroidInjector<Fragment> {
return fragmentInjector
}


private fun init() {
initDagger()
}

private fun initDagger() {
applicationComponent = DaggerAppComponent
.builder()
.application(this)
.applicationModule(AppModule(this))
.build()

applicationComponent.inject(this)
}

}

应用模块:

@Module
class AppModule(private val application: SellerHubApplication) {

@Provides
@Singleton
fun provideApplication(): Application {
return application
}
}

关于android - Dagger 2的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59194329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com