带参数的Dagger2注入类(使用Room)

时间:2019-02-21 19:46:03

标签: android kotlin dagger-2 android-room

我在用Dagger2注入类时遇到问题。我正在使用RoomDatabase进行数据库访问。

我的房间设置:

Dao的

interface noteDao()
interface noteTypeDao()
interface userDao()

NoteRepository

@Singleton
class NoteRepository @Inject constructor(
    private val noteDao: NoteDao,
    private val noteTypeDao: NoteTypeDao,
    private val userDao: UserDao
) {

}

AppDatabase

@Database(entities = [Note::class, User::class, NoteType::class], version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun noteDao(): NoteDao
    abstract fun userDao(): UserDao
    abstract fun noteTypeDao(): NoteTypeDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "NoteDatabase"
                ).build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

匕首2设置:

AppModule

@Module
class AppModule {

    @Provides
    fun provideNoteRepository(app: Application): NoteRepository {
        return NoteRepository(
            AppDatabase.getDatabase(app).noteDao(),
            AppDatabase.getDatabase(app).noteTypeDao(),
            AppDatabase.getDatabase(app).userDao()
        )
    }

    @Provides
    fun provideApplication(): Application {
        return Application()
    }

}

AppComponent

@Component(modules = [AppModule::class])
interface AppComponent {
    fun inject(app: MainActivity)
}

我在第AppDatabase行的context.applicationContext中得到了一个N​​ullPointerExeption int。建议如何解决问题? 似乎AppDatabase无法从Dagger2获取应用程序实例。

1 个答案:

答案 0 :(得分:2)

Application是一个框架类,您不能只通过调用其构造函数来实例化它。相反,您需要将框架实例化的应用程序传入模块中,并提供以下信息:

@Module
class AppModule(val application: Application) { 
    ...

    @Provides
    fun provideApplication(): Application {
        return application
    }
}

现在,如果您以前像这样创建AppComponent,请在应用程序的onCreate中创建(大概是这样做的通常方法):

override fun onCreate() {
    injector = DaggerAppComponent.create()
}    

您必须将其替换为以下内容,将您的应用程序实例传递给模块,以便随后可以提供它:

override fun onCreate() {
    injector = DaggerAppComponent.builder()
            .appModule(appModule(this))
            .build()
}