Injecting Named Dependencies within Constructor
See original GitHub issueHello,
Is there a way to inject a named dependency within a constructor? And if not, do you have a recommended way of doing this? Let’s say I have the following:
val myModule = applicationContext {
bean("A") { MyComponent() }
bean("B") { MyComponent() }
bean { MyOtherComponent() }
}
And I have an object that I is instantiated using constructor injection:
class MyThirdComponent(val componentA: MyComponent, val otherComponent: MyOtherComponent) {
...
}
How would I specify which MyComponent
I want in the MyThirdComponent
constructor? I see in the docs how to specify which named component when injecting directly into other beans but not into a constructor.
I see some potential workarounds:
- Not use construction injection on
MyThirdComponent
and create a bean instead:
val myModule = applicationContext {
...
bean { MyThirdComponent(get("A"), get()) }
}
It defeats the purpose of constructor injection and requires two maintenance points (if I change the constructor of MyThirdComponent
I would need to change the bean instantiation as well), but it could potentially work.
- Inject what I can with the constructor, and then have
MyThirdComponent
extendKoinComponent
and finish off the other injections withby inject
:
class MyThirdComponent(val otherComponent: MyOtherComponent) : KoinComponent {
val componentA: MyComponent by inject("A")
...
}
It’s slightly more tedious but all of the injection is in one place and there’s no need to create an unnecessary bean in this case.
Am I missing something here/is there a better solution? If not, do you have any recommendations/thoughts on the above? I haven’t tested any of these solutions yet, and I just started playing around with Koin today so this might be wrong… My apologies if this has been answered already, I searched the docs / issues and couldn’t find anything on this subject.
Merci! Julien
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:5 (1 by maintainers)
FYI
get()
was updated and accepts aQualifier
instead of aString
. So the new solution would be:What is the reason behind that? Does using KoinComponent have slower performance? Or maybe slower compile time?