0
# Dependency Injection
1
2
Core dependency injection functionality for resolving and managing object instances.
3
4
## Capabilities
5
6
### Instance Resolution
7
8
Core methods for retrieving dependencies from the Koin container.
9
10
```kotlin { .api }
11
/**
12
* Get a dependency instance immediately
13
* @param qualifier - Optional qualifier to distinguish multiple instances
14
* @param parameters - Optional parameters to pass to the factory function
15
* @return Instance of the requested type
16
* @throws NoDefinitionFoundException if no definition is found
17
*/
18
inline fun <reified T : Any> Koin.get(qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null): T
19
20
/**
21
* Get a dependency instance or null if not found
22
* @param qualifier - Optional qualifier to distinguish multiple instances
23
* @param parameters - Optional parameters to pass to the factory function
24
* @return Instance of the requested type or null
25
*/
26
inline fun <reified T : Any> Koin.getOrNull(qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null): T?
27
28
/**
29
* Get a dependency instance by class
30
* @param clazz - Class type to resolve
31
* @param qualifier - Optional qualifier
32
* @param parameters - Optional parameters
33
* @return Instance of the requested type
34
*/
35
fun <T> Koin.get(clazz: KClass<*>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null): T
36
37
/**
38
* Get a dependency instance by class or null if not found
39
* @param clazz - Class type to resolve
40
* @param qualifier - Optional qualifier
41
* @param parameters - Optional parameters
42
* @return Instance of the requested type or null
43
*/
44
fun <T> Koin.getOrNull(clazz: KClass<*>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null): T?
45
```
46
47
**Usage Examples:**
48
49
```kotlin
50
import org.koin.core.context.startKoin
51
import org.koin.core.parameter.parametersOf
52
import org.koin.core.qualifier.named
53
import org.koin.dsl.module
54
55
// Service definitions
56
class UserService(private val apiKey: String)
57
class DatabaseClient
58
class EmailService
59
60
val appModule = module {
61
single { DatabaseClient() }
62
single(named("primary")) { EmailService() }
63
factory { (apiKey: String) -> UserService(apiKey) }
64
}
65
66
startKoin { modules(appModule) }
67
68
// Get instances
69
val database = koin.get<DatabaseClient>()
70
val emailService = koin.get<EmailService>(named("primary"))
71
val userService = koin.get<UserService> { parametersOf("api-key-123") }
72
73
// Safe resolution
74
val optionalService = koin.getOrNull<SomeOptionalService>()
75
```
76
77
### Lazy Injection
78
79
Lazy dependency resolution for deferred initialization.
80
81
```kotlin { .api }
82
/**
83
* Get a lazy dependency that will be resolved on first access
84
* @param qualifier - Optional qualifier to distinguish multiple instances
85
* @param mode - Thread safety mode for the lazy delegate
86
* @param parameters - Optional parameters to pass to the factory function
87
* @return Lazy delegate that resolves the dependency on first access
88
*/
89
inline fun <reified T : Any> Koin.inject(qualifier: Qualifier? = null, mode: LazyThreadSafetyMode = KoinPlatformTools.defaultLazyMode(), noinline parameters: ParametersDefinition? = null): Lazy<T>
90
91
/**
92
* Get a lazy dependency that may be null
93
* @param qualifier - Optional qualifier to distinguish multiple instances
94
* @param mode - Thread safety mode for the lazy delegate
95
* @param parameters - Optional parameters to pass to the factory function
96
* @return Lazy delegate that resolves the dependency or null on first access
97
*/
98
inline fun <reified T : Any> Koin.injectOrNull(qualifier: Qualifier? = null, mode: LazyThreadSafetyMode = KoinPlatformTools.defaultLazyMode(), noinline parameters: ParametersDefinition? = null): Lazy<T?>
99
```
100
101
**Usage Examples:**
102
103
```kotlin
104
import org.koin.core.component.KoinComponent
105
import org.koin.core.component.inject
106
import org.koin.core.parameter.parametersOf
107
108
class UserController : KoinComponent {
109
// Lazy injection - resolved on first access
110
private val userService: UserService by inject()
111
private val emailService: EmailService by inject(named("primary"))
112
113
// Lazy injection with parameters
114
private val apiClient: ApiClient by inject { parametersOf("endpoint.url") }
115
116
// Optional lazy injection
117
private val optionalService: OptionalService? by injectOrNull()
118
119
fun handleRequest() {
120
// Services are resolved here on first access
121
val user = userService.getCurrentUser()
122
emailService.sendWelcome(user)
123
}
124
}
125
```
126
127
### Multiple Instances
128
129
Retrieve all instances of a given type.
130
131
```kotlin { .api }
132
/**
133
* Get all instances of a given type
134
* @return List of all instances matching the type
135
*/
136
inline fun <reified T> Koin.getAll(): List<T>
137
138
/**
139
* Get all instances of a given class
140
* @param clazz - Class type to resolve
141
* @return List of all instances matching the class
142
*/
143
fun <T> Koin.getAll(clazz: KClass<*>): List<T>
144
```
145
146
**Usage Examples:**
147
148
```kotlin
149
import org.koin.dsl.module
150
import org.koin.core.qualifier.named
151
152
interface NotificationProvider
153
class EmailNotificationProvider : NotificationProvider
154
class SmsNotificationProvider : NotificationProvider
155
class PushNotificationProvider : NotificationProvider
156
157
val notificationModule = module {
158
single<NotificationProvider>(named("email")) { EmailNotificationProvider() }
159
single<NotificationProvider>(named("sms")) { SmsNotificationProvider() }
160
single<NotificationProvider>(named("push")) { PushNotificationProvider() }
161
}
162
163
// Get all notification providers
164
val allProviders = koin.getAll<NotificationProvider>()
165
println("Found ${allProviders.size} notification providers")
166
```
167
168
### Runtime Declaration
169
170
Declare instances at runtime for dynamic dependency registration.
171
172
```kotlin { .api }
173
/**
174
* Declare an instance at runtime
175
* @param instance - Instance to declare
176
* @param qualifier - Optional qualifier
177
* @param secondaryTypes - Additional types this instance can be resolved as
178
* @param allowOverride - Whether to allow overriding existing definitions
179
*/
180
inline fun <reified T> Koin.declare(instance: T, qualifier: Qualifier? = null, secondaryTypes: List<KClass<*>> = emptyList(), allowOverride: Boolean = true)
181
```
182
183
**Usage Examples:**
184
185
```kotlin
186
import org.koin.core.qualifier.named
187
188
// Dynamically declare instances
189
val dynamicConfig = ConfigurationService("production")
190
koin.declare(dynamicConfig, named("runtime"))
191
192
// Declare with additional types
193
interface Logger
194
class FileLogger : Logger
195
val logger = FileLogger()
196
koin.declare(logger, secondaryTypes = listOf(Logger::class))
197
198
// Later retrieve the declared instances
199
val config = koin.get<ConfigurationService>(named("runtime"))
200
val loggerInstance = koin.get<Logger>()
201
```
202
203
### Property Management
204
205
Manage application properties within the Koin container.
206
207
```kotlin { .api }
208
/**
209
* Get a property value with a default fallback
210
* @param key - Property key
211
* @param defaultValue - Default value if property is not found
212
* @return Property value or default value
213
*/
214
fun <T : Any> Koin.getProperty(key: String, defaultValue: T): T
215
216
/**
217
* Get a property value or null if not found
218
* @param key - Property key
219
* @return Property value or null
220
*/
221
fun <T : Any> Koin.getProperty(key: String): T?
222
223
/**
224
* Set a property value
225
* @param key - Property key
226
* @param value - Property value
227
*/
228
fun Koin.setProperty(key: String, value: Any)
229
230
/**
231
* Delete a property
232
* @param key - Property key to delete
233
*/
234
fun Koin.deleteProperty(key: String)
235
```
236
237
**Usage Examples:**
238
239
```kotlin
240
import org.koin.dsl.module
241
242
// Use properties in module definitions
243
val configModule = module {
244
single { DatabaseClient(getProperty("db.url", "localhost:5432")) }
245
single { ApiClient(getProperty<String>("api.endpoint")) }
246
}
247
248
// Set properties at runtime
249
koin.setProperty("feature.enabled", true)
250
koin.setProperty("max.connections", 100)
251
252
// Use properties in code
253
val isFeatureEnabled = koin.getProperty("feature.enabled", false)
254
val maxConnections = koin.getProperty<Int>("max.connections")
255
256
// Check if property exists
257
val optionalSetting = koin.getProperty<String>("optional.setting")
258
if (optionalSetting != null) {
259
println("Optional setting: $optionalSetting")
260
}
261
262
// Delete properties
263
koin.deleteProperty("temporary.flag")
264
```
265
266
### Module Management
267
268
Load and unload modules dynamically at runtime.
269
270
```kotlin { .api }
271
/**
272
* Load modules into the container
273
* @param modules - List of modules to load
274
* @param allowOverride - Whether to allow overriding existing definitions
275
* @param createEagerInstances - Whether to create eager instances immediately
276
*/
277
fun Koin.loadModules(modules: List<Module>, allowOverride: Boolean = true, createEagerInstances: Boolean = false)
278
279
/**
280
* Unload modules from the container
281
* @param modules - List of modules to unload
282
*/
283
fun Koin.unloadModules(modules: List<Module>)
284
285
/**
286
* Create all eager instances
287
*/
288
fun Koin.createEagerInstances()
289
```
290
291
**Usage Examples:**
292
293
```kotlin
294
import org.koin.dsl.module
295
296
// Define modules
297
val testModule = module {
298
single { TestService() }
299
}
300
301
val productionModule = module {
302
single { ProductionService() }
303
}
304
305
// Load modules dynamically
306
when (environment) {
307
"test" -> koin.loadModules(listOf(testModule))
308
"production" -> koin.loadModules(listOf(productionModule), createEagerInstances = true)
309
}
310
311
// Later unload test modules
312
if (environment != "test") {
313
koin.unloadModules(listOf(testModule))
314
}
315
316
// Manually trigger eager instance creation
317
koin.createEagerInstances()
318
```
319
320
### Container Lifecycle
321
322
Manage the Koin container lifecycle.
323
324
```kotlin { .api }
325
/**
326
* Close the Koin container and cleanup all resources
327
*/
328
fun Koin.close()
329
```
330
331
**Usage Examples:**
332
333
```kotlin
334
// Close container when application shuts down
335
Runtime.getRuntime().addShutdownHook(Thread {
336
koin.close()
337
})
338
```
339
340
## Type Definitions
341
342
```kotlin { .api }
343
/**
344
* Type alias for parameter definition functions
345
*/
346
typealias ParametersDefinition = () -> ParametersHolder
347
348
/**
349
* Container for dependency injection parameters
350
*/
351
class ParametersHolder {
352
/** List of parameter values */
353
val values: List<Any?>
354
355
/** Whether to use indexed parameter access */
356
val useIndexedValues: Boolean?
357
358
/** Get parameter by index */
359
operator fun <T> get(i: Int): T
360
361
/** Set parameter by index */
362
fun <T> set(i: Int, t: T)
363
364
/** Get parameter by type */
365
inline fun <reified T : Any> get(): T
366
367
/** Get optional parameter by type */
368
inline fun <reified T : Any> getOrNull(): T?
369
370
/** Parameter count */
371
fun size(): Int
372
373
/** Check if empty */
374
fun isEmpty(): Boolean
375
376
/** Check if not empty */
377
fun isNotEmpty(): Boolean
378
}
379
380
/**
381
* Create parameter holder from values
382
* @param parameters - Variable number of parameter values
383
* @return ParametersHolder containing the parameters
384
*/
385
fun parametersOf(vararg parameters: Any?): ParametersHolder
386
387
/**
388
* Create empty parameter holder
389
* @return Empty ParametersHolder
390
*/
391
fun emptyParametersHolder(): ParametersHolder
392
```