Search code examples
dagger-2dagger

Creating dependent component in dagger 2


I have a project with one AppComponent that builds and works. Now I want to add another dependent component to the project.

I add a scope annotation

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

Then I create some class and a module for it

class A {
    fun get() = 1
}

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

After I add the dependent component like this

@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)
}

If I try to build it I see the next error error: @Component.Builder is missing setters for required modules or components: [AppComponent]

Here is how my AppComponent looks like

@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)
}

Any idea what's wrong?


Solution

  • When you create a builder to your dependent component never mark a setter of your main component with @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)
    }