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
(如上所述,MyRepository
在core
模块中)
这里是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。 ...
您需要将Dagger与AAC ViewModel类一起使用的几个步骤: