Dagger2 + ViewModel + 存储库
Dagger2 + ViewModel + Repository
我是 Dagger 2 的新手,正在尝试在 Kotlin 中实现它。在这里,我试图将我的存储库对象注入到视图模型中。我成功地能够以这种方式注入它
public class LoginViewModel @Inject constructor(var mApplication: Application, var repository: LoginRepository) :
ViewModel() {
这是我的存储库的样子
class LoginRepository @Inject constructor(val retrofit: APICallInterface) {
这是我的模块的样子
@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)
}
我无法理解的是 Dagger 2 如何能够为存储库提供对象,因为我没有在任何带有 @Provides 注释的模块中提到它。
我已经尝试关注许多博客和这里提供的几个 stckoverflow 问题,但是 none 解决了我的疑问。
任何 help/explanation 将不胜感激。
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.
您通过使用 @Inject
:
注释构造函数来使用构造函数注入
[@Inject
] Identifies injectable constructors, methods, and fields.
因此,通过添加注解,Dagger 可以识别构造函数并知道如何在需要时创建对象。
class LoginRepository @Inject constructor(..)
如果你的构造函数没有注释 那么 你需要在模块中有一个 @Provides
注释的方法,以便 Dagger 可以访问依赖项,但是您应该主要对需要额外设置 and/or 初始化的对象使用 @Provides
注释方法。
我是 Dagger 2 的新手,正在尝试在 Kotlin 中实现它。在这里,我试图将我的存储库对象注入到视图模型中。我成功地能够以这种方式注入它
public class LoginViewModel @Inject constructor(var mApplication: Application, var repository: LoginRepository) :
ViewModel() {
这是我的存储库的样子
class LoginRepository @Inject constructor(val retrofit: APICallInterface) {
这是我的模块的样子
@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)
}
我无法理解的是 Dagger 2 如何能够为存储库提供对象,因为我没有在任何带有 @Provides 注释的模块中提到它。
我已经尝试关注许多博客和这里提供的几个 stckoverflow 问题,但是 none 解决了我的疑问。
任何 help/explanation 将不胜感激。
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.
您通过使用 @Inject
:
[
@Inject
] Identifies injectable constructors, methods, and fields.
因此,通过添加注解,Dagger 可以识别构造函数并知道如何在需要时创建对象。
class LoginRepository @Inject constructor(..)
如果你的构造函数没有注释 那么 你需要在模块中有一个 @Provides
注释的方法,以便 Dagger 可以访问依赖项,但是您应该主要对需要额外设置 and/or 初始化的对象使用 @Provides
注释方法。