Search code examples
androidkotlindependency-injectiondagger-hilt

Problems with Hilt DI


Sorry for seally question, I have never used Dagger/Hilt before. Can't understand how to inject dependencies in my app. Here is what have now:

@InstallIn(Application::class)
@Module
abstract class RepositoryModule {
    @Binds
    abstract fun bindProductRepository(productRepository: ProductRepository): IProductRepository

    @Binds
    abstract fun bindCategoryStorage(categoryStorage: CategoryStorageImpl) : CategoryStorage

    companion object {
        @Provides
        @Singleton
        fun createRoomDataBase(@ApplicationContext context: Context) : ProductRoomDatabase = ProductRoomDatabase.getDatabase(context)

        @Provides
        @Singleton
        fun createProductDao(productRoomDatabase: ProductRoomDatabase) = productRoomDatabase.productDao()

        @Provides
        @Singleton
        fun createCategoryDao(productRoomDatabase: ProductRoomDatabase) = productRoomDatabase.categoryDao()
    }
}

Solution

  • Hilt comes with three pre-made components:

    ApplicationComponent | SingletonComponent - component that contains application-level dependencies and live until application lives.

    ActivityComponent - component that contains Activity-level dependencies

    FragmentComponent - component that contains Fragment level dependencies

    InstallIn annotation suggests that all dependendencies in the current module will be available in the argument of the annotation.