9

I am new at the dependency injection on Android. I am using Dagger-Hilt and in AppModule class that I generated for the DB providers I got an error and the project doesn't compile.

The error is @InstallIn can only be used on @Module or @EntryPoint classes This is my AppModule object. Where do I make mistake?

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

@Singleton
@Provides
fun provideAppDatabase(
    @ApplicationContext app: Context
) = Room.databaseBuilder(
    app,
    AppDatabase::class.java,
    "gelirkenal"
).build()

@Singleton
@Provides
fun provideItemDao(db: AppDatabase) = db.itemDao()
}
Progman
  • 16,827
  • 6
  • 33
  • 48
enesigneci
  • 301
  • 1
  • 4
  • 13

5 Answers5

24

I set a import of Module as following:

import com.google.android.datatransport.runtime.dagger.Module

But the below is correct:

import dagger.Module

user3813078
  • 459
  • 3
  • 7
8

Change the following imports:

import com.google.android.datatransport.runtime.dagger.Module
import com.google.android.datatransport.runtime.dagger.Binds

To =>

import dagger.Module
import dagger.Binds
Harjan
  • 533
  • 1
  • 6
  • 24
charlie.7
  • 329
  • 3
  • 5
5

change ApplicationComponent::class to SingletonComponent::class and also you can find more hilt generated components by referring this Hilt Generated Components

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

@Singleton
@Provides
fun provideAppDatabase(
    @ApplicationContext app: Context
) = Room.databaseBuilder(
    app,
    AppDatabase::class.java,
    "gelirkenal"
).build()

@Singleton
@Provides
fun provideItemDao(db: AppDatabase) = db.itemDao()
}
ajithvgiri
  • 199
  • 2
  • 5
0

It looks like you add @InstallIn annotation to not related class in your project.

i30mb1
  • 3,894
  • 3
  • 18
  • 34
  • 2
    I just added the `@InstallIn` annotation into AppModule. Also added `@HiltAndroidApp` to Application class, `@AndroidEntryPoint` to Activities and Fragments, `@ViewModelInject` to ViewModel constructor. Where is the mistake? – enesigneci Dec 13 '20 at 09:17
0

In my case, import was incorrect

from:

import com.google.android.datatransport.runtime.dagger.Module
import com.google.android.datatransport.runtime.dagger.Provides

to:

import dagger.Module
import dagger.Provides
c-an
  • 3,543
  • 5
  • 35
  • 82