Lecture 9
Lecture 9
Koin
Author:Semen Naduiev
What is Dependency Injection (DI)
A design pattern used to reduce coupling between classes by injecting their dependencies from
the outside rather than creating them inside the class.
Why Use DI?
✅ Improves testability
✅ Reduces boilerplate
1. Constructor Injection
class Car(val engine: Engine)
2. Field Injection (used with libraries like Dagger/Hilt)
@Inject lateinit var engine: Engine
3. Setter Injection
class Car {
fun setEngine(engine: Engine) { ... }
}
DI Frameworks in Android
Kodein (modular)
What is Inversion of Control (IoC)?
Inversion of Control (IoC) is a design principle in which control over program flow is inverted —
instead of a class controlling its dependencies, the control is handed over to a framework or
external code.
Traditional vs IoC Example
How IoC is Applied
The Service Locator is a design pattern that provides dependencies by accessing a centralized registry or
"locator".
📌 How it works:
✅ Pros:
● Simple to implement.
● Centralized place to manage dependencies.
❌ Cons:
Code Generation is an automated approach where tools like Hilt or Dagger generate code to
handle dependency creation and injection.
📌 How it works:
Pros:
Full support for IoC — objects don’t create their own dependencies.
No global state.
❌ Cons:
Learning curve.
bind<Type>()
Provides a type alias for the object so it can be injected as another interface.
override = true
implementation( "io.insert-koin:koin-core:$koin_version")
Koin vs Dagger/Hilt (Comparison)
Summary