Koin is a DSL to help describe your modules & definitions, a container to make definition resolution. What we need now is an API to retrieve our instances outside of the container. That's the goal of Koin components.
KoinComponent interface is here to help you inject your instances where you current technical stack doesn"t offer it. Avoid to use it if you can use
Create a Koin Component
To give a class the capacity to use Koin features, we need to tag it with
KoinComponent interface. Let's take an example.
A module to define MyService instance
we start Koin before using definition.
Start Koin with myModule
Here is how we can write our
MyComponent to retrieve instances from Koin container.
Use get() & by inject() to inject MyService instance
Unlock the Koin API with KoinComponents
Once you have tagged your class as
KoinComponent, you gain access to:
by inject()- lazy evaluated instance from Koin container
get()- eager fetch instance from Koin container
setProperty()- get/set property
Retrieving definitions with get & inject
Koin offers two ways of retrieving instances from the Koin container:
val t : T by inject()- lazy evaluated delegated instance
val t : T = get()- eager access for instance
The lazy inject form is better to define property that need lazy evaluation.
Resolving instance from its name
If you need you can specify the following parameter with
qualifier- name of the definition (when specified name parameter in your definition)
Example of module using definitions names:
We can make the following resolutions:
No inject() or get() in your API?
If your are using an API and want to use Koin inside it, just tag the desired class with