在匕首2中创建从属组件

时间:2018-07-21 19:23:11

标签: dagger-2 dagger

我有一个项目,其中一个AppComponent可以构建和运行。现在,我想向项目添加另一个依赖组件。

我添加了范围注释

@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class MyTestScope

然后我为其创建一些类和一个模块

class A {
    fun get() = 1
}

@Module
class TestModule {
    @Provides
    @MyTestScope
    fun provideA(): A {
        return A()
    }
}

像这样添加相关组件之后

@MyTestScope
@Component(dependencies = [AppComponent::class],
    modules = [TestModule::class])
interface DependentComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        fun appComponent(component: AppComponent): Builder
        fun build(): DependentComponent
     }

     fun inject(application: Application)
}

如果我尝试构建它,则会看到下一个错误 error: @Component.Builder is missing setters for required modules or components: [AppComponent]

这是我的AppComponent的样子

@Singleton
@Component(modules = [ 
     AndroidInjectionModule::class,
     ActivityModule::class,
     // etc ....
])
interface AppComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        fun language(language: Language): Builder
        @BindsInstance
        fun appContext(appContext: Context): Builder
        fun build(): AppComponent
    }

    fun inject(application: Application)
}

你知道怎么了吗?

1 个答案:

答案 0 :(得分:2)

当您为依赖组件创建构建器时,从不@BindsInstance

标记主要组件的设置器
@MyTestScope
@Component(dependencies = [AppComponent::class],
    modules = [TestModule::class])
interface DependentComponent {
    @Component.Builder
    interface Builder {
        fun appComponent(component: AppComponent): Builder
        fun build(): DependentComponent
    }

    fun inject(application: Application)
}