Dagger2无法为应用程序对象绑定BindsInstance [英] Dagger2 fails to BindsInstance for application object

查看:228
本文介绍了Dagger2无法为应用程序对象绑定BindsInstance的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我关注这篇文章是为了使Dagger 2可以直接为我创建一个模块。但是我一直收到此错误:

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:

@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



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



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?

推荐答案

Dagger无法创建模块,因为它没有空的默认构造函数。相反,您将其声明为类AppModule(私有val应用程序:Application),因此您需要手动创建模块并将其添加到组件中,并根据错误提示进行操作。

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()

尽管这绑定了应用程序,但您不添加模块—并且如前所述,Dagger无法创建它,因为您声明了构造函数参数。

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.

这篇关于Dagger2无法为应用程序对象绑定BindsInstance的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆