Injekt
Next gen dependency injection library for Kotlin.
@Provide fun jsonParser() = JsonParser()
interface Http
@Provide class HttpImpl : Http
@Provide class Api(private val http: Http, private val jsonParser: JsonParser)
@Provide class Repository(private val api: Api)
@Provide data class AppDependencies(val repository: Repository)
fun main() {
val dependencies = create<AppDependencies>()
dependencies.repo
}
Setup
plugins {
id("io.github.ivianuu.injekt") version latest_version
}
dependencies {
implementation("io.github.ivianuu.injekt:core:${latest_version}")
implementation("io.github.ivianuu.injekt:common:${latest_version}")
}
Providers
You can provide dependencies by annotating them with @Provide:
(baseUrl: BaseUrl)
(logger: Logger) {
()
}
: OkHttpClient = ...
apiKey: ApiKey = ...
{
}
Scoping
The core of Injekt doesn't know anything about scoping, but there is a api in the common module.
You have to annotate your class or the return type of a function or a property with @Scoped tag.
@Provide @Scoped<UiScope> class MyViewModel
Then you have to provide a Scope instance.
object UiScope
Then you can inject your class.
@Provide val uiScope = Scope<UiScope>()
fun onCreate() {
val db = create<MyViewModel>()
}
Later it should be disposed like so.
fun onDestroy() {
uiScope.dispose()
}
Multi injection
You can inject all dependencies of a given type by injecting a List<T>
@Provide fun singleElement(): String = "a"
@Provide fun multipleElements(): Collection<String> = listOf("b", "c")
fun main {
create<List<String>>() == listOf(, , )
}
Function injection
Sometimes you want to delay the creation, need multiple instances, want to provide additional parameters,
or to break circular dependencies.
You can do this by injecting a function.
@Provide class (tokenFactory: () -> Token) {
tokenA = tokenFactory()
tokenB = tokenFactory()
}
(viewModelFactory: (String) -> MyViewModel) {
viewModel lazy { viewModelFactory() }
}
( bar: Bar)
(foo: (Bar) -> Foo) {
foo = foo()
}
Distinguish between types
Sometimes you have multiple dependencies of the same type
Injekt will need help to keep them apart here are three strategies:
Errors / Debugging
Injekt will show an error if there are missing dependencies.
Additionally it will dump generated code in a kotlin like syntax in the /build/injekt/dump folder
for each file where injections happen
More complex uses can be found in my essentials project(base project for my apps)
https://github.com/IVIanuu/essentials