DataModule的:
@Module
class DataModule constructor(application: App){
private var db : Database = Room.databaseBuilder(application.applicationContext,
Database::class.java, "database.db")
.build()
@Provides
@PerApplication
fun provideDatabase(): Database {
return db
}
应用:
class App : DaggerApplication() {
@Inject lateinit var activityDispatchingAndroidInjector: DispatchingAndroidInjector<Activity>
override fun onCreate() {
super.onCreate()
setupTimber()
// setupCrashlytics()
RxPaparazzo.register(this)
}
override fun applicationInjector(): AndroidInjector<out App> {
return DaggerApplicationComponent.builder()
.dataModule(DataModule(this)).create(this)
}
ApplicationComponent:
@PerApplication
@Component(modules = [AndroidSupportInjectionModule::class, ActivityBindingModule::class, ApplicationModule::class, DataModule::class, ServiceModule::class])
interface ApplicationComponent : AndroidInjector<App> {
@Component.Builder
abstract class Builder : AndroidInjector.Builder<App>()
}
我收到错误:
Error:(21, 2) error: @Component.Builder is missing setters for required modules or components: [com.org.injection.module.DataModule]
public static abstract class Builder extends dagger.android.AndroidInjector.Builder<com.org.App> {
^
答案 0 :(得分:6)
发生这种情况,因为您已声明,DataModule
需要一个应用程序对象的实例才能构建,但您尚未指定如何创建该模块。如果@Module
带注释的类在其构造函数中具有不任何参数(即具有默认构造函数),则dagger将创建该模块。否则,您必须指定如何手动创建模块。
将最顶层(应用程序)组件更改为以下:
@Component(modules = [...])
interface AppComponent {
@Component.Builder
interface Builder {
// @BindsInstance will make `application` to be accessible in the graph
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
}
现在更改DataModule
以请求应用程序对象的实例:
@Module
class DataModule {
@Provides
fun provideDatabase(application: Application): Database {
return ...
}
}