android - 通过依赖注入(inject)来注入(inject)公共(public)类是个好方法吗?

标签 android kotlin dependency-injection instance koin

注入(inject) viewModels存储库 fragment Utils和.. .但是使用依赖注入(inject)KoinDagger-hilt<来注入(inject)通用class是个好方法吗?/

假设我们要在fragment中使用StringBuilder()

第一种方法:

我们可以注入(inject)

val otherModule= module {
   single { StringBuilder() }
}

并在fragment中使用它,如下所示:

class Fragment : BaseFragment(){
  private val mPassword : StringBuilder by inject()
}

第二种方法:

我们可以创建 实例而无需注入(inject)

class Fragment : BaseFragment(){
    private var mPassword = StringBuilder()
 }

我的问题是第一种方法对我们来说是常见的方法吗?

最佳答案

我想说这要看情况。 Di 背后的主要目标/概念是实现 S.O.L.I.D 的第一原则,或者如 freecodecamp.org 所说:

It is the fifth principle of S.O.L.I.D — the five basic principles of object-oriented programming and design by Uncle Bob — which states that a class should depend on abstraction and not upon concretions (in simple terms, hard-coded).

According to the principles, a class should concentrate on fulfilling its responsibilities and not on creating objects that it requires to fulfill those responsibilities. And that’s where dependency injection comes into play: it provides the class with the required objects.

提供了另一个很好的答案here ,因为已经讨论了何时不使用依赖注入(inject)。

现在我的观点是:如果可能的话,尝试注入(inject)那些必须经常使用的依赖项,如果可能的话,通过构造函数注入(inject)来注入(inject)它们。这样,您可以轻松查看您的类使用了哪些依赖项。尽量不要注入(inject)使用过一次的类或者通用语言类。

关于android - 通过依赖注入(inject)来注入(inject)公共(public)类是个好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64291385/

相关文章:

android - 如何在 Android 中的第二个 Activity 中获取 Facebook session ?

Kotlin - 将集合转换为数组列表

c# - 如何将 appsettings.json 文件添加到我的 Azure Function 3.0 配置中?

java - 如何使用Spring在Helper类中获取 Autowiring 的bean

c# - 如何在 Azure Functions 中混合使用自定义参数绑定(bind)和依赖项注入(inject)?

android - 如何从 Preferences 子屏幕移回到 PreferenceFragmentCompat 中的主屏幕?

android - 使用 HoloEverywhere 构建 Android Studio 项目失败

android - 在Android上运行Lua代码

java - Java < 15 和 >= 15 的不同 Nashorn 引擎?

android - RecyclerView.OnItemClickListener 与在 RecyclerView 的查看器中实现 onClickListener?