What is Koin.dart?
Koin is pragmatic lightweight dependency injection framework for Dart developers. Written in pure Dart, using functional resolution as key concept. Koin.dart is a port of the original version written in Kotlin.
Start the container
Once you have declared your definitions within Koin modules, your are ready to start the Koin container.
The startKoin function
startKoin function is the main entry point to launch Koin container. It need a list of Koin modules to run.
Modules are loaded and definitions are ready to be resolved by the Koin container.
startKoin has been called, Koin will read all your modules & definitions. Koin is then ready for any
by inject() call to retrieve the needed instance.
Your Koin container can have several options:
logger- to enable logging - see <<logging.adoc#_logging,logging>> section
startKoin can't be called more than once. If you need several point to load modules, use the
Behind the start - Koin instance under the hood
When we start Koin, we create a
KoinApplication instance that represents the Koin container configuration instance. Once launched, it will produce a
Koin instance resulting of your modules and options.
Koin instance is then hold by the
GlobalContext, to be used by any
GlobalContext is a default JVM context strategy for Koin. It's not accessible anymore directly, as we need a component to manage different kind of context:
KoinContextHandler is responsible to register and give access to the underlying KoinContext. It's called by
startKoin to register a new
GlobalContext. This will allow us to register a different kind of context, in the perspective of Koin Multiplatform.
KoinContextHandler is then ready once
startKoin has finished.
Loading modules after startKoin
You can't call the
startKoin function more than once. But you can use directly the
This function is interesting for SDK makers who want to use Koin, because they don't need to use the
starKoin() function and just use the
loadKoinModules at the start of their library.
it's possible also to unload a bunch of definition, and then release theirs instance with the given function:
Koin context isolation
For SDK Makers, you can also work with Koin in a non global way: use Koin for the DI of your library and avoid any conflict by people using your library and Koin by isolating your context.
In a standard way, we can start Koin like that:
From this, we can use the
KoinComponent as it: it will use the
GlobalContext Koin instance.
But if we want to use an isolated Koin instance, you can just declare it like follow:
You will have to keep your
myApp instance avilable in your library and pass it to your custom KoinComponent implementation:
And now, you register your context and run your own isolated Koin components:
Stop Koin - closing all resources
You can close all the Koin resources and drop instances & definitions. For this you can use the
stopKoin() function from anywhere, to stop the Koin
Else on a
KoinApplication instance, just call