简体   繁体   English

Dagger 2 什么注射什么不注射

[英]Dagger 2 what to inject and what not

I've been reading for a few hours but I can't find an answer.我已经阅读了几个小时,但我找不到答案。 What things should I inject and what things not?我应该注射什么东西,不应该注射什么东西?

I have my LoginViewModel with a few injected dependencies but I'm not sure if I have to inject for example my User data class (among other data classes) or just instantiate it.我的LoginViewModel带有一些注入的依赖项,但我不确定是否必须注入例如我的User数据 class (以及其他数据类)或只是实例化它。

LoginViewModel.kt登录视图模型.kt

class LoginViewModel @Inject constructor(
    private val loginRepositoryImpl: LoginRepositoryImpl,
    private val baseApplication: BaseApplication,
    private val networkUtils: NetworkUtils,
    private val sharedPreferences: SharedPreferences) : ViewModel() {

    fun processLogin(username: String, password: String) {
        val user = User(username, password)
        ...
    }
    ...
}

User.kt用户.kt

data class User (
    @SerializedName("usuario")
    var user: String,
    @SerializedName("clave")
    var password: String = "",
    @SerializedName("nombre")
    var name: String = ""
)

Depends why you are using Dagger.取决于您使用 Dagger 的原因。 Say you want to test the following code.假设您要测试以下代码。 loginRepositoryImpl could be accessing an authentication service over network so you'd want to provide an alternate implementation. loginRepositoryImpl 可能正在通过网络访问身份验证服务,因此您需要提供替代实现。 User is just a data class, there is no value in providing a mock implementation.用户只是一个数据 class,提供模拟实现没有任何价值。

    fun processLogin(username: String, password: String): Boolean {
        val user = User(username, password)
        val isValidLogin = loginRepositoryImpl.login(user)
        return isValidLogin
        ...
    }

well mate no you don't need to inject your user data and why are you injecting your base application doesn't sound right好伙伴不,您不需要注入您的用户数据,为什么要注入您的基础应用程序听起来不正确

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

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