1

In :app module

@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
    @Component.Factory
    interface Factory {
        fun create(@BindsInstance context: Context): AppComponent
    }
}    
@Module
class AppModule {
    @Singleton
    @Provides
    fun provideA() = A()
}

In dynamic feature module

@Component(
        dependencies = [AppComponent::class],
        modules = [FeatureModule::class]
)
interface FeatureComponent{
    @Component.Factory
    interface Factory {
        fun create(appComponent: AppComponent): FeatureComponent
    }

    fun inject(fragment: HomeFragment)

}
@Module
class FeatureModule {
}

In HomeFragment or HomeViewModel, I can't inject object A (provided in AppModule in AppComponent). How to resolve it?

Thanks.

PhongBM
  • 799
  • 10
  • 23

1 Answers1

0

When you use Dagger's component dependencies (as you are doing), when FeatureComponent depends on AppComponent, then AppComponent needs to expose the dependencies using provision functions so that FeatureComponent can inject them.

Provision functions are just functions in the component interface, for example:

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

    fun provideA(): A // <--- this is a provision function, you need to add this to expose "A" from AppComponent

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance context: Context): AppComponent
    }
}

Just like other functions in Dagger Modules, names of these functions don't matter. However their return types and qualifiers (if there is any) matter.

You can also extract these provision functions to other interfaces and make your AppComponent extend those other interfaces in order to keep your code base organised, just like in this sample project.

From the docs:

When a type is used as a component dependency, each provision method on the dependency is bound as a provider. Note that only the bindings exposed as provision methods are available through component dependencies.

Mustafa Berkay Mutlu
  • 1,929
  • 1
  • 25
  • 37