DependencyResolutionContext

Basic resolver of dependencies for constructor-based dependency injection.

Intentionally quite restricted to promote predictability and ease of understanding:

  • Only Kotlin classes with a primary constructor can be automatically constructed from a class reference. Other types are added as values or unambiguous function references (e.g. to a constructor or factory function).

  • No optional parameters allowed (though they can be ignored with @DoNotResolve).

  • Dependencies are resolvable either by type or by name, not both.

  • No ambiguous resolution. If two values are valid an exception is thrown instead.

Simple example:

// Given a set of classes depending on each other...
class CheeseRepository
class CheeseService(private val cheeseRepository: CheeseRepository)
class App(private val cheeseService: CheeseService)

// ...you can construct a context...
val context = DependencyResolutionContext.Builder().add(
CheeseRepository::class,
CheeseService::class,
App::class
).build()

// ...and get the instances you need (probably the constructed app).
// You can throw away the context afterwards if you don't need it.
val app = context.get<App>()

Types

Link copied to clipboard
class Builder

Builder class for DependencyResolutionContext

Functions

Link copied to clipboard
inline fun <T> get(): T
fun <T> get(jClass: Class<T>): T

Get a value of type T from the resolution context.

inline fun <T> get(name: String): T
fun <T> get(name: String, jClass: Class<T>): T

Get a named value of type T from the resolution context