Dagger2 fails to BindsInstance for application obj

2019-08-25 04:57发布

I'm following this article in order to make Dagger 2 to directly create a module for me. However I keep getting this error:

Error:(10, 1) error: @Component.Builder is missing setters for required modules or components: [stalker.commons.di.app.AppModule]

I've search around but, although there are similar questions, none of the answers seemed to apply for me. Below is my implementation:

AppComponent.kt

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

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

        fun build(): AppComponent
    }

}

AppModule.kt

@Module(
        subcomponents = [
            (LoginSubComponent::class),
            (RegisterSubComponent::class),
            (ForgotPasswordSubComponent::class),
            (HomepageSubComponent::class)
        ]
)
class AppModule (private val application: Application){

    @Provides
    @Singleton
    fun providesDefaultFieldValidator(): DefaultFieldValidator = DefaultFieldValidator()

}

App.kt

class App : DaggerApplication() {

    override fun onCreate() {
        super.onCreate()
        (applicationInjector() as AppComponent).inject(this)
        plant(Timber.DebugTree())
    }

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerAppComponent.builder()
                .application(this)
                .build()
    }

}

Any idea what I've might be doing wrong?

2条回答
唯我独甜
2楼-- · 2019-08-25 05:27

Dagger can't create your module because it does not have an empty default constructor. Instead you declare it as class AppModule (private val application: Application), so you need to manually create the module and add it to the component—as hinted by the error.

DaggerAppComponent.builder()
            .application(this) // bind application to component builder
                // where is the module?
            .build()

While this binds the application, you do not add the module—and as mentioned Dagger can't create it because you declared constructor arguments.

It seems like you're not using the constructor argument, so just delete it and it will work.

查看更多
别忘想泡老子
3楼-- · 2019-08-25 05:43

I guess it is because of the fact that you have your custom constructor that takes Application as parameter

try adding

fun appModule(application: Application): Builder

to your

@Component.Builder
interface Builder {

and initialize it when you create the component in your Application subclass

override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
    return DaggerAppComponent.builder()
            .application(this)
            .appModule(AppModule(this))
            .build()
}
查看更多
登录 后发表回答