简体   繁体   English

Dagger 2:没有任何提供者的现场注入

[英]Dagger 2: Field Injection without any provider

While working on a project that uses Dagger 2 for DI, I tried to create a ViewModel and field inject it even without creating any provider from any module.在处理一个使用 Dagger 2 进行 DI 的项目时,我尝试创建一个ViewModel并现场注入它,即使没有从任何模块创建任何提供程序。 Biggest confusing moment for me since as far as I know Dagger needs to know how to construct something before using @Inject .对我来说最大的困惑时刻,因为据我所知,Dagger 在使用@Inject之前需要知道如何构造一些东西。

This is the example Activity and ViewModel class这是示例 Activity 和 ViewModel class

class MainActivity : DaggerAppCompatActivity(){

  @Inject
  lateinit var viewModel: MainViewModel

  //accessing viewModel methods

}


class MainViewModel @Inject constructor(val sharedPref: SharedPrefManager) : ViewModel() {

 //some public methods...

}

Here the sharedPref was provided using @Provides inside a module so no question there, but how can this code works and run perfectly with the MainViewModel ?这里sharedPref是在模块内使用@Provides提供的,所以毫无疑问,但是这段代码如何与MainViewModel一起工作并完美运行? No instantiation at all, no use of ViewModelProvider and Factory.根本没有实例化,没有使用 ViewModelProvider 和 Factory。 Can someone explain to me what is happening behind the scene?有人可以向我解释幕后发生了什么吗?

Note: I could also remove the parameters in the constructor and ended up with this without any problem (I guess).注意:我也可以删除构造函数中的参数并最终没有任何问题(我猜)。

class MainViewModel @Inject constructor(): ViewModel() { class MainViewModel @Inject constructor(): ViewModel() {

 //some public methods...

}

I am guessing this ViewModel is not aware of the lifecycle as it has no lifecycleOwner我猜这个 ViewModel 不知道生命周期,因为它没有lifecycleOwner

It seems I finally found the answer which is a very important part.看来我终于找到了答案,这是一个非常重要的部分。 But I still wanted to know how does Dagger knew how to create a ViewModel which is too specific and part of Android framework without providers.但我仍然想知道 Dagger 是如何知道如何创建一个 ViewModel 的,它太具体并且是 Android 框架的一部分,没有提供者。

https://www.vogella.com/tutorials/Dagger/article.html#defining-dependencies-object-consumers https://www.vogella.com/tutorials/Dagger/article.html#defining-dependencies-object-consumers

https://stackoverflow.com/a/32081400/12204620 https://stackoverflow.com/a/32081400/12204620

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM