Dagger 2:多模块项目,注入依赖项,但在运行时收到“ lateinit属性存储库尚未初始化”错误

问题描述 投票:2回答:1

Dagger版本是2.25.2。

我有两个Android项目模块:core模块和app模块。

core模块中,我为匕首CoreComponent定义了]]

app模块中,我有AppComponent用于匕首。

CoreComponet在核心项目模块中:

@Component(modules = [MyModule::class])
@CoreScope
interface CoreComponent {
   fun getMyRepository(): MyRepository
}

在核心项目模块中,我有一个存储库类,它不属于任何匕首模块,但在其构造函数旁边使用@Inject批注:

class MyRepository @Inject constructor() {
   ...
}

我的应用程序组件:

@Component(modules = [AppModule::class], dependencies = [CoreComponent::class])
@featureScope
interface AppComponent {
    fun inject(activity: MainActivity)
}

MainActivity中:

class MainActivity: AppCompatActivity() {

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

        val coreComponent = DaggerCoreComponent.builder().build()

        DaggerAppComponent
                  .builder()
                  .coreComponent(coreComponent)
                  .build()
                  .inject(this)
     }

}

我的项目是MVVM体系结构,通常:

  • [MainActivity主机MyFragment

  • [MyFragment引用为MyViewModel

  • MyViewModel具有依赖项MyRepository(如上所述,MyRepositorycore模块中)

  • 这里是MyViewModel

class MyViewModel : ViewModel() {
    // Runtime error: lateinit property repository has not been initialize
    @Inject
    lateinit var repository: MyRepository

    val data = repository.getData()

}

[MyViewModel在MyFragment中初始化:

class MyFragment : Fragment() {
   lateinit var viewModel: MyViewModel

   override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
        ...
    }
}

当我运行我的应用程序时,它因运行时错误而崩溃:

kotlin.UninitializedPropertyAccessException: lateinit property repository has not been initialize

该错误告诉我,匕首依赖项注入不适用于我的设置。所以,我想念什么?如何摆脱这个错误?

====更新=====

我尝试过:

class MyViewModel @Inject constructor(private val repository: MyRepository): ViewModel() {
        val data = repository.getData()
    }

现在,当我运行应用程序时,出现新错误:

Caused by: java.lang.InstantiationException: class foo.bar.MyViewModel has no zero argument constructor

Dagger版本是2.25.2。我有两个Android项目模块:核心模块和应用程序模块。在核心模块中,我为匕首定义了CoreComponent,在应用程序模块中,我为匕首定义了AppComponent。 ...

android kotlin dagger-2 kotlin-android-extensions
1个回答
0
投票

您需要将Dagger与AAC ViewModel类一起使用的几个步骤:

© www.soinside.com 2019 - 2024. All rights reserved.