如何在Android中使用Dagger 2从应用程序组件获取对象?



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

此项目仅包含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对象?

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

我以这种方式更改了我的 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()

相关内容

最新更新