Reputation: 13668
For example I the following classes:
abstract class BaseClass()
class SpecificClass : BaseClass()
Now, I want to provide SpecificClass
through koin
dependency inject but I also want to provide the base class BaseClass
in the same graph.
To be clear I want to do something like:
class Someclass {
...
private specificClass: SpecificClass by inject()
...
}
class Someclass {
...
private baseClass: BaseClass by inject()
// where this BaseClass is just the the same instace of the SpecificClass in the dependency graph
...
}
How do I do my module to do this? How can I inject the implementation instance to the baseClass reference?
Upvotes: 6
Views: 3336
Reputation: 6353
You can do it using Koin in 2 ways
Methodn 1
You can create dependencies for both of them like this
single {
SpecificClass()
}
single<BaseClass> {
get<SpecificClass>()
}
In this way, whenever you inject an instance, it will get injected accordingly
Method 2
You can make use of named dependencies like this
single("BaseClassImpl") {
SpecificClass()
}
And when you want to inject it, provide key for that dependency like this:
class Someclass {
...
private specificClass: SpecificClass by inject("BaseClassImpl")
...
}
class Someclass {
...
private baseClass: BaseClass by inject("BaseClassImpl")
// where this BaseClass is just the the same instace of the SpecificClass in the dependency graph
...
}
Upvotes: 7
Reputation: 660
You can't inject abstract classes.
In order to inject a class, it must be instantiable and abstract classes are not.
To inject SpecificClass
with Koin you need to create a module:
val appModule = module {
single {
SpecificClass()
}
}
Initialize it in your application class:
class MyApplication : Application() {
override fun onCreate(){
super.onCreate()
// start Koin!
startKoin {
// declare used Android context
androidContext(this@MyApplication)
// declare modules
modules(appModule)
}
}
}
And use the inject delegation in your activity/fragment
class MyActivity() : AppCompatActivity() {
val specificClass : SpecificClass by inject()
}
Upvotes: 0