首页 > 解决方案 > 如何在 Android 中使用 Dagger 2 从应用程序组件中获取对象?

问题描述

我正在做一个非常糟糕的 Android 项目。它的所有 Singletons 类都遵循错误的模式。所以,我正在努力让它变得更好。

该项目仅包含app模块(因此它不是多模块项目)。

这些是我添加的:

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

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance applicationContext: Context): AppComponent
    }

}

@Module
object AppModule {

    @Singleton
    @Provides
    @JvmStatic
    fun provideAppContext(context: Context) = context

    @Singleton
    @Provides
    @JvmStatic
    fun provideAppDataManager(ctx: Context) = AppDataManager.setupInstance(ctx)

}

class SiteFinderApplication : Application() {

    val component: AppComponent by lazy {
        DaggerAppComponent
                .factory()
                .create(this)
    }

    override fun onCreate() {
        super.onCreate()

    }

}

因此,根据我的理解AppDataManager,当用户启动应用程序时正在创建对象。如果我的假设是正确的,那么我的问题是如何AppDataManager在我的其他活动中从 Application 组件中获取对象?

标签: androiddagger-2

解决方案


好的,我找到了方法。对于其他有同样问题的人,可以做这样的事情。

我以这种方式更改了我的 AppComponent 类:

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

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance applicationContext: Context): AppComponent
    }

    fun getAppDataManager(): AppDataManager
}

从我的活动中,我可以得到AppDataManager这样的结果:

appDataManager = (application as SiteFinderApplication).component.getAppDataManager()

推荐阅读