Koin如何在Android活动/appcompatactivity之外进行注入 [英] Koin how to inject outside of Android activity / appcompatactivity

查看:132
本文介绍了Koin如何在Android活动/appcompatactivity之外进行注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Koin 是用于DI的新的轻量级库,可以使用在Android以及独立的Kotlin应用中.

Koin is a new, lightweight library for DI and can be used in Android as well as in standalone kotlin apps.

通常,您会像这样注入依赖项:

Usually you inject dependencies like this:

class SplashScreenActivity : Activity() {

    val sampleClass : SampleClass by inject()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }
}

使用inject()方法.

但是,在无法使用活动"上下文的地方(即活动外部)注入东西怎么办?

But what about injecting stuff in places where Activity context is not available i.e. outside of an Activity?

推荐答案

KoinComponent可以解决.在任何课程中,您都可以简单地:

There is the KoinComponent which comes to the rescue. In any class you can simply:

class SampleClass : KoinComponent {

    val a : A? by inject()
    val b : B? by inject()
}

扩展KoinComponent使您可以访问inject()方法.

Extending KoinComponent gives you access to inject() method.

请记住,通常以通常的方式注入东西就足够了:

Remember that usually it's enough to inject stuff the usual way:

class SampleClass(val a : A?, val b: B?)

这篇关于Koin如何在Android活动/appcompatactivity之外进行注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆