android - 如何在 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 组件中获取对象?
解决方案
好的,我找到了方法。对于其他有同样问题的人,可以做这样的事情。
我以这种方式更改了我的 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()
推荐阅读
- reactjs - 放置“ScrollToTop”组件的正确位置是什么?
- python - 如何使用python覆盖或删除文件中的一行
- c# - 如何在 WPF 中使用 DI 来拥有一个新的 istance 而不询问容器
- c# - 如何确定该程序集是从 f# 项目编译的?
- react-native - 已解决反应导航不起作用反应本机
- go - chromedp fails to start a new instance of chrome
- html - 动画 svg 渐变设置为背景图像
- javascript - 根据条件和索引从数组中删除元素
- angular - TS 和 HTML 之间的 FormGroup 绑定
- java - 创建谓词以将实体与 Map 属性中的条目匹配