https://kotlinlang.org logo
#koin
Title
# koin
d

Dan Rusu

01/28/2023, 8:22 PM
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

Big Chungus

01/28/2023, 8:57 PM
Export your lib as a koin module that your consumers can simply add to their koin config
d

Dan Rusu

01/28/2023, 9:16 PM
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

Big Chungus

01/28/2023, 9:56 PM
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

Dan Rusu

01/28/2023, 9:57 PM
I see. Thanks
a

arnaud.giuliani

01/30/2023, 9:05 AM
@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

Big Chungus

01/30/2023, 9:14 AM
Clever!
d

Dan Rusu

01/31/2023, 5:03 PM
@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

arnaud.giuliani

02/01/2023, 8:56 AM
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 👍
78 Views