Modules Definitions
Writing definitions in Koin is done via Dart functions, that describe ishow is built your instance. Once you have configured your Koin application, let's write some modules and definitions.
Module & definitions
Given some classes that we need to inject:
Here how we could define some components:
Qualifiers
You can give a qualifier to a component. This qualifier can be a string or a type, and is setup with the named()
function:
This qualifier can be associated to a class or directly to a type:
Additional types
In the module API, for a definition, you can give some extra type to bind, with the bind
operator (binds
for list of Class):
Then you can request your instance with get<Component1>()
or get<ComponentInterface1>()
.
You can bind multiple definitions with the same type:
But here you won't be able to request an instance with get<ComponentInterface1>()
. You will have to use koin.bind<Component1,ComponentInterface1>()
to retrieve an instance of ComponentInterface1
, with the Component1
implementation.
Note that you cal also look for all components binding a given type: getAll<ComponentInterface1>()
will request all instances binding ComponentInterface1
type.
Combining several modules
There is no concept of import in Koin. Just combine several complementary modules definitions.
Let's dispatch definitions in 2 modules:
We just need to list them for Koin:
Loading after start
After Koin has been started with startKoin { }
function, it is possible to load extra definitions modules with the following function: loadKoinModules(modules...)
Dropping definitions
Once a modules has been loaded into Koin, we can unload it and then drop definitions and instances, related to those definitions. for this we use the unloadKoinModules(modules...)
Declare on the fly
Allows you to declare an instance on the fly with Koin already initialized or in a scope already created.
You can also use a qualifier or secondary types to help create your definition:
Recap
A quick recap of the Koin keywords:
module()
- create a Koin Module or a submodule (inside a module)factory()
- provide a factory bean definitionsingle()
- provide a single bean definitionget()
- resolve a component dependencynamed()
- define a qualifier with type, enum or stringbind()
- additional Dart type binding for given bean definitionbinds()
- list of additional Dart types binding for given bean definition