简体   繁体   中英

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. Biggest confusing moment for me since as far as I know Dagger needs to know how to construct something before using @Inject .

This is the example Activity and 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 ? No instantiation at all, no use of ViewModelProvider and 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() {

 //some public methods...

}

I am guessing this ViewModel is not aware of the lifecycle as it has no 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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