jane
jane

Reputation: 124

Hilt - app cannot be provided without an @Inject constructor or an @Provides-annotated method

This is my hilt module:

@Module
@InstallIn(SingletonComponent::class)
object AppModule {

    @Provides
    @Singleton
    fun provideDatabase(app: App) =
        Room.databaseBuilder(app, AppDatabase::class.java, "app_database").build()

    @Provides
    fun provideUserDao(database: AppDatabase) = database.userDao()

    @Provides
    @Singleton
    fun provideApi(): ContactsService {
        return Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(MoshiConverterFactory.create(
                Moshi.Builder().build()))
            .build()
            .create(ContactsService::class.java)
    }

    @Provides
    @Singleton
    fun provideRepository(api:ContactsService,dao: ContactsDao): ContactRepository{
        return ContactRepositoryImpl(api,dao)
    }
}

This is the indicated App class:

@HiltAndroidApp
class App : Application() {
}

This is the error I get:

 ..\assignment\App_HiltComponents.java:128: error: [Dagger/MissingBinding] com.example.assignment.App cannot be provided without an @Inject constructor or an @Provides-annotated method.

I double check every class that I use injection and in each of them I used @Inject annotation. I read every stack question but none of them solved my problem.

Upvotes: 0

Views: 1029

Answers (1)

Aleksei Sinelnikov
Aleksei Sinelnikov

Reputation: 631

Hilt is built on top of the DI library Dagger. Dagger works only with a specific type of class.

Hilt provides @ApplicationContext as Context type.

You should provide your App explicitly.

@Provides
fun provideApp(@ApplicationContext context: Context): App = context as App

Upvotes: 2

Related Questions