Search code examples
androiddependency-injectiondagger

Dagger Scope issue


I am trying to set dagger up to provide a data module but I keep running into this error :

error: @Modules cannot be scoped. Did you mean to scope a method instead? @javax.inject.Singleton() ^

Here is the culprit module :

package com.bottlerocket.dependancyinjection.modules


import android.content.Context
import androidx.room.Room
import com.bottlerocket.dependancyinjection.DI
import com.data.api.BottleRocketApi
import com.data.cache.StoreCache
import com.data.database.CacheDataStoreObject
import com.data.database.RemoteStoreDataObject
import com.data.database.StoreDatabase
import com.data.repository.StoreRepositoryImplementation
import dagger.Module
import dagger.Provides
import interfaces.StoresRepository
import javax.inject.Named
import javax.inject.Singleton

@Module
@Singleton
class DataModule {

    @Singleton
    @Provides
    fun provideRoomDatabase(context: Context): StoreDatabase {
        return Room.databaseBuilder(
            context,
            StoreDatabase::class.java,
            "stores_db"
        ).build()
    }

    @Provides
    @Singleton
    fun provideStoreRepository(
        api: BottleRocketApi,
        @Named(DI.inMemoryCache) cache: StoreCache
    ): StoresRepository {

        val cachedMoviesDataStore = CacheDataStoreObject(cache)
        val remoteMoviesDataStore = RemoteStoreDataObject(api)
        return StoreRepositoryImplementation(cachedMoviesDataStore, remoteMoviesDataStore)
    }
}

Solution

  • As the error indicates, you can't annotate a module with @Singleton, only the functions. So all you have to do is remove the annotation from your module.

    Change

    @Module
    @Singleton
    class DataModule {
    }
    

    with

    @Module
    class DataModule {
    }
    

    This check was introduced in a recent version of Dagger.