I am new to Dagger 2 and trying to implement it in Kotlin. Here i am trying to inject my repository object into viewmodel. I am successfully able to inject it this way
public class LoginViewModel @Inject constructor(var mApplication: Application, var repository: LoginRepository) :
ViewModel() {
This is how my repository looks like
class LoginRepository @Inject constructor(val retrofit: APICallInterface) {
This is how my module looks like
@Module
class BaseModule {
@Provides
fun getRetrofit(): APICallInterface {
return Retrofit.Builder()
.baseUrl("https://samples.openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.build().create(APICallInterface::class.java)
}
What i am unable to understand is how Dagger 2 is able to provide an object for repository as i have not mentioned it in any module with @Provides annotation.
I have tried following many blogs and few stckoverflow questions available here but none of them is solving my doubt.
Any help/explanation will be appreciated.
What i am unable to understand is how Dagger 2 is able to provide an object for repository as i have not mentioned it in any module with @Provides annotation.
You're using constructor injection by annotating the constructor with @Inject
:
[
@Inject
] Identifies injectable constructors, methods, and fields.
So, by adding the annotation, Dagger becomes aware of the constructor and knows how to create the object when needed.
class LoginRepository @Inject constructor(..)
If your constructor wouldn't have the annotation on it then you'd need a @Provides
annotated method in a module so that Dagger can access the dependency, but you should use @Provides
annotated methods primarily for objects that need additional setup and/or initialization.