首页 > 解决方案 > 无法弄清楚如何在我的应用程序中使用匕首。似乎是循环依赖的情况

问题描述

以下是我的应用程序的依赖关系图。GameView 构造函数如下所示

class GameView (
    private var gameActivity: GameActivity,
    private val screenWidth: Int,
    private val screenHeight: Int
) : SurfaceView(gameActivity), Runnable {
}

GameView 构造函数将 GameActivity 实例作为参数。这是循环依赖的情况吗?因为GameActivity的依赖是GameView,而GameView的依赖也是GameActivity。如何解决这些循环依赖。有人可以分享处理这种情况的代码吗? 在此处输入图像描述 在上面的依赖图中,如果我想将 GameView 实例传递给 ShooterPlane,这将导致依赖循环。如何避免这种依赖循环?源代码链接 https://github.com/kpradeepkumarreddy/DaggerBirdShooter

标签: androidkotlindependency-injectiondagger-2

解决方案


如果您有循环依赖,我发现的唯一解决方案是
Lazy<T>在 ShooterPlane中使用更多信息在 dagger2 文档 中然后当您需要在 shooterPlane 中的 GameView 时使用 Lazy.get

class ShooterPlane(private val gameView: Lazy<GameView>) {
fun someMethod(){
    gameView.get().someMethodInGameView()
}

该解决方案的不便之处在于 Injection 直接影响您构造函数的参数。但这是工作,我认为他们是避免这种缺点的一些技巧


推荐阅读