gpt4 book ai didi

android - 我很难理解 Dagger。有人能告诉我这个 Kodein 实现在 Dagger 中的样子吗?

转载 作者:行者123 更新时间:2023-11-29 22:58:01 27 4
gpt4 key购买 nike

我需要为一个新项目学习 Dagger 2,并且我正在努力理解这一切。

我看过一些教程,这些教程提供了一些清晰度,但我仍然对很多内容感到困惑,例如各种移动部分(组件、模块、注入(inject)器、提供程序)如何相互关联。

我在想,也许如果有人可以向我展示使用 Kodein 进行依赖注入(inject)的以下代码的 Dagger 等效实现,那将有助于弥合我在理解上的差距:

注入(inject).kt

fun depInject(app: Application): Kodein {
return lazy {
bind<Application>() with instance(app)
bind<Context>() with instance(app.applicationContext)
bind<AnotherClass>() with instance(AnotherClass())
}
}

BaseApplication.kt

class BaseApplication: Application() {

companion object {
lateinit var kodein: Kodein
private set
}

override fun onCreate() {
super.onCreate()
kodein = depInject(this)
}
}

然后在我需要注入(inject)的任何地方我只使用:

 private val context: Context by BaseApplication.kodein.instance()

谢谢!

最佳答案

fun depInject(app: Application): AppComponent {
return lazy {
DaggerAppComponent.factory().create(app)
}
}

@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
fun context(): Context

@Component.Factory
interface Factory {
fun create(@BindsInstance app: Application): AppComponent
}
}

@Module
object AppModule {
@Provides
@JvmStatic
fun context(app: Application): Context = app.applicationContext
}

然后

class BaseApplication: Application() {

companion object {
lateinit var component: AppComponent
private set
}

override fun onCreate() {
super.onCreate()
component = depInject(this)
}
}

private val context: Context by lazy { BaseApplication.component.context() }

编辑:

@Singleton class AnotherClass @Inject constructor() {
}

@Singleton
@Component(/*...*/)
interface AppComponent {
...

fun anotherClass(): AnotherClass

...
}

关于android - 我很难理解 Dagger。有人能告诉我这个 Kodein 实现在 Dagger 中的样子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203985/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com