简体   繁体   English

Dagger2 + ViewModel +存储库

[英]Dagger2 + ViewModel + Repository

I am new to Dagger 2 and trying to implement it in Kotlin. 我是Dagger 2的新手,正在尝试在Kotlin中实现它。 Here i am trying to inject my repository object into viewmodel. 在这里,我试图将我的存储库对象注入到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. 我无法理解的是Dagger 2如何能够为存储库提供对象,因为我在任何带有@Provides注释的模块中都没有提到它。

I have tried following many blogs and few stckoverflow questions available here but none of them is solving my doubt. 我尝试过跟踪许多博客,这里没有几个stckoverflow问题,但是没有一个问题可以解决我的疑问。

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. 我无法理解的是Dagger 2如何能够为存储库提供对象,因为我在任何带有@Provides注释的模块中都没有提到它。

You're using constructor injection by annotating the constructor with @Inject : 您正在通过@Inject注释构造函数来使用构造函数注入:

[ @Inject ] Identifies injectable constructors, methods, and fields. [ @Inject ]标识可注入的构造函数,方法和字段。

So, by adding the annotation, Dagger becomes aware of the constructor and knows how to create the object when needed. 因此,通过添加注释,Dagger知道了构造函数,并且知道如何在需要时创建对象。

 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. 如果您的构造函数上没有注释, 您需要在模块中使用@Provides注释的方法,以便Dagger可以访问依赖项,但您应该将@Provides注释的方法主要用于需要其他设置和/或对象的对象初始化。

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

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