What's the best practice for using Koin when creat...
# koin
d
What's the best practice for using Koin when creating libraries? I'm just starting to explore Koin and noticed that I need to initialize everything with
startKoin
but libraries don't typically have a main entry point so I'm wondering how to approach DI when creating libraries
b
Export your lib as a koin module that your consumers can simply add to their koin config
d
Thanks. I prefer to avoid requiring library users to use a DI framework so I wonder if maybe I'm going in the wrong direction if that's the case. One use-case that I'm trying to tackle is to allow users of the library to create an instance of a class by calling the constructor and the class would use property injection to get a random number generator. All the test classes would have that dependency bound to a fake random number generator so that I could specify the sequence of random numbers and validate that the random numbers are used correctly by the class.
b
If you don't expect your consumers to use di then you should not use it in the lib. It's just not a common practice for libraries
d
I see. Thanks
a
@Big Chungus you need to go with isolated context: https://insert-koin.io/docs/reference/koin-core/context-isolation
this way you have your own Koin context, whatever people have on their own
b
Clever!
d
@arnaud.giuliani Thanks! A couple questions about that approach: 1. The CustomKoinComponent is an abstract class which prevents using DI in subclasses. Is there a reason why that can't be an interface instead? 2. The library has many entry points so I'm not sure where would be a good place to initialize the koin app. Can I initialize it directly in MyKoinContext singleton (and re-assign that variable from tests)?
a
The CustomKoinComponent is an abstract class which prevents using DI in subclasses. Is there a reason why that can’t be an interface instead?
You are already depend on
KoinComponent
interface. Here you provide your framework implementation with an abstract class. You need to keep a
Koin
instance under the hand
Can I initialize it directly in MyKoinContext singleton (and re-assign that variable from tests)?
Yes, up to you to keep this Koin instance where you need and can get access easily. With that you can configure it for tests 👍
109 Views