使用 Dagger2 获取应用上下文
Get Application context with Dagger2
我使用 MVP 模式创建了一个应用程序,我需要有应用程序的上下文才能访问 getString() 方法。
为此,我使用 Dagger2 除了我不知道如何实现它
所以这是我到目前为止所做的事情:
BaseApplication.kt
class BaseApplication: Application() {
lateinit var component: ApplicationComponent
override fun onCreate() {
super.onCreate()
instance = this
component = buildComponent()
component.inject(this)
}
fun buildComponent(): ApplicationComponent {
return DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(this))
.build()
}
fun getApplicationComponent(): ApplicationComponent {
return component
}
companion object {
lateinit var instance: BaseApplication private set
}
}
ApplicationComponent.kt
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun inject(application: Application)
}
ApplicationModule.kt
@Module
class ApplicationModule(private val context: Context) {
@Singleton
@Provides
@NonNull
fun provideContext(): Context {
return context
}
}
我想将 BaseApplication 的上下文提供到我的 recyclerview 的适配器中,因为我需要访问 getString 方法。
我已经完成此操作以在我的适配器中获取上下文,现在我必须做什么?
要在 dagger 中提供 applicationContext
,请创建一个新范围。
@javax.inject.Qualifier
annotation class ForApplication
然后在您的 ApplicationModule
中,您使用范围提供此依赖项。
@Singleton
@Provides
@NonNull
@ForApplication
fun provideContext(): Context {
return context
}
现在,在任何您想使用此上下文的地方,只需在其前面加上此范围。例如
@Inject
class YourAdapter extends Adapter {
YourAdapter(@ForApplication Context context) {
}
}
我使用 MVP 模式创建了一个应用程序,我需要有应用程序的上下文才能访问 getString() 方法。 为此,我使用 Dagger2 除了我不知道如何实现它
所以这是我到目前为止所做的事情:
BaseApplication.kt
class BaseApplication: Application() {
lateinit var component: ApplicationComponent
override fun onCreate() {
super.onCreate()
instance = this
component = buildComponent()
component.inject(this)
}
fun buildComponent(): ApplicationComponent {
return DaggerApplicationComponent.builder()
.applicationModule(ApplicationModule(this))
.build()
}
fun getApplicationComponent(): ApplicationComponent {
return component
}
companion object {
lateinit var instance: BaseApplication private set
}
}
ApplicationComponent.kt
@Component(modules = arrayOf(ApplicationModule::class))
interface ApplicationComponent {
fun inject(application: Application)
}
ApplicationModule.kt
@Module
class ApplicationModule(private val context: Context) {
@Singleton
@Provides
@NonNull
fun provideContext(): Context {
return context
}
}
我想将 BaseApplication 的上下文提供到我的 recyclerview 的适配器中,因为我需要访问 getString 方法。
我已经完成此操作以在我的适配器中获取上下文,现在我必须做什么?
要在 dagger 中提供 applicationContext
,请创建一个新范围。
@javax.inject.Qualifier
annotation class ForApplication
然后在您的 ApplicationModule
中,您使用范围提供此依赖项。
@Singleton
@Provides
@NonNull
@ForApplication
fun provideContext(): Context {
return context
}
现在,在任何您想使用此上下文的地方,只需在其前面加上此范围。例如
@Inject
class YourAdapter extends Adapter {
YourAdapter(@ForApplication Context context) {
}
}