注射匕首2时缺少绑定

时间:2019-02-25 13:49:59

标签: android kotlin dagger-2

我在Dagger 2中遇到此错误

C:\ Users \ Anon \ AndroidStudioProjects \ BarreChat1082 \ app \ build \ tmp \ kapt3 \ stubs \ debu g \ com \ example \ barrechat108 \ Dependencies \ RepositoryComponent.java:8:错误: [Dagger / MissingBinding] com.example.barrechat108.MainActivity不能为 无需@Inject构造函数或@Provides注释方法即可提供。

public abstract interface RepositoryComponent {
            ^
  com.example.barrechat108.MainActivity is injected at
      com.example.barrechat108.Dependencies.RepositoryComponent.inject(com.example.barrechat108.MainActivity)

我以为我已经正确设置了注入,我的模块是

@Module
class RepositoryModule {

//Provide singleton instance of our database for use by entire app.
//Set up in application's onCreate method
@Provides
@Singleton
fun providesDatabase(applicationContext: Application) : AppDatabase {
    val db = Room.databaseBuilder(
        applicationContext,
        AppDatabase::class.java, "AppDatabase"
    ).build()
    return db
}

@Provides
@Singleton
fun providesRepository(database: AppDatabase) : Repository {
    val repos = Repository(database)
    return repos
}


}

@Module
class AppModule (application: Application) {

val mApplication = application

@Provides
@Singleton
fun providesApplication() : Application {
    return mApplication
}

}

用于注入MainActivity的组件是

@Singleton
@Component(modules=[AppModule::class, RepositoryModule::class])
interface RepositoryComponent{
    fun inject(activity: MainActivity)
}

包含错误的位置。

要构建Dagger2的实例,我从Application类进行了扩展,并在清单中告诉应用程序使用此代码,

class BarreApp : Application() {

private lateinit var mRepositoryComponent: RepositoryComponent

override fun onCreate() {
    super.onCreate()

    mRepositoryComponent = DaggerRepositoryComponent.builder()
        .appModule(AppModule(this))
        .repositoryModule(RepositoryModule())
        .build()
}

fun getRepositoryComponent(): RepositoryComponent {
    return mRepositoryComponent
}


}

最后,我使用数据注入的活动是MainActivity。在此主要活动中,我将创建存储库的实例,并将其从该开始活动发送到视图模型。通过检查存储库是否已在viewmodel中设置,我摆脱了重新分配。因此,每次MainActiviy进行创建时,它都会打开viewmodel并检查是否有一个存储库,如果没有,则将其注入的存储库拉入并放入ViewModel。

class MainActivity : AppCompatActivity() {

private lateinit var mPager: ViewPager

@Inject
private lateinit var mRepository: Repository

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(findViewById(R.id.barreBar))

    //Get Repository Component using Dagger2
    val mApp = application as BarreApp
    mApp.getRepositoryComponent().inject(this)

    //Get the main ViewModel
    val barreViewModel = ViewModelProviders.of(this).get(BarreViewModel :: class.java)

    //Add repository to ViewModel
    barreViewModel.setRepository(mRepository)

}

0 个答案:

没有答案