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)
}
}
with the inject()
method.
But what about injecting stuff in places where Activity context is not available i.e. outside of an Activity?
There is the
KoinComponent
which comes to the rescue. In any class you can simply:Extending
KoinComponent
gives you access toinject()
method.Remember that usually it's enough to inject stuff the usual way:
Koin provides a solution for this using the
KoinComponent
interface. For example, if you need to get some dependencies in your repository then you can simply implement the KoinComponent interface. It gives you access to various Koin features such asget()
andinject()
. Use KoinComponent only when you can't rewrite the constructor to accept dependencies as constructor parameters.Constructor injection is better than this approach.
For example, the same thing can be achieved by:
And you can add the definition for instantiating this class in a koin module: