Simple Kotlin injection under 30 lines
// Register dependency on App start.
DependencyInjection.register<UserRepository> { ApiUserRepository }
// Get it later on.
val userRepository = DependencyInjection.getDependency<UserRepository>()
- Simple & type-safe api (generics FTW)
- Lightweight: 1 file ~ 30 lines of pure kotlin
- Does NOT rely on evil Annotations
- Copy and paste
Inje.kt
file in your project. - Make sure you import the
kotlin-reflect
on which Inject relies:
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
- There is no step 3 \o/
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
// Register your dependency by providing
// a concrete object for a given Interface.
DependencyInjection.register<UserRepository> { ApiUserRepository }
}
}
class UserFragment : Fragment(), HasDependencies {
// Get your dependency.
val userRepository: UserRepository = getDependency()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Use it!
userRepository.doSomeCoolStuff()
}
}