Dagger 2: Field Injection without any provider

911 Views Asked by At

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

1

There are 1 best solutions below

0
On

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