0
# Component Integration & Injection
1
2
Component integration interfaces and extension functions for seamless dependency injection into classes and objects. Provides both lazy and direct injection patterns with full type safety.
3
4
## Capabilities
5
6
### KoinComponent Interface
7
8
Base interface for classes that need dependency injection capabilities.
9
10
```kotlin { .api }
11
/**
12
* Base component interface for Koin integration
13
* Provides access to the Koin container for dependency resolution
14
*/
15
interface KoinComponent {
16
/**
17
* Get the Koin instance
18
* @return Current Koin instance
19
*/
20
fun getKoin(): Koin
21
}
22
```
23
24
**Usage Examples:**
25
26
```kotlin
27
import org.koin.core.component.KoinComponent
28
import org.koin.core.component.inject
29
import org.koin.core.component.get
30
31
class UserController : KoinComponent {
32
// Lazy injection - resolved on first access
33
private val userService: UserService by inject()
34
35
// Direct injection - resolved immediately
36
private val logger = get<Logger>()
37
38
fun createUser(userData: UserData): User {
39
logger.info("Creating user")
40
return userService.create(userData)
41
}
42
}
43
44
class DataProcessor : KoinComponent {
45
override fun getKoin(): Koin {
46
// Custom Koin instance if needed
47
return customKoinInstance
48
}
49
}
50
```
51
52
### Lazy Dependency Injection
53
54
Inject dependencies lazily using delegate properties.
55
56
```kotlin { .api }
57
/**
58
* Lazy inject dependency with optional qualifier and parameters
59
* @param qualifier - Optional qualifier to distinguish instances
60
* @param mode - Thread safety mode for lazy initialization
61
* @param parameters - Optional parameters for dependency creation
62
* @return Lazy delegate for the dependency
63
*/
64
inline fun <reified T> KoinComponent.inject(
65
qualifier: Qualifier? = null,
66
mode: LazyThreadSafetyMode = LazyThreadSafetyMode.SYNCHRONIZED,
67
noinline parameters: ParametersDefinition? = null
68
): Lazy<T>
69
70
/**
71
* Lazy inject dependency with nullable result
72
* @param qualifier - Optional qualifier to distinguish instances
73
* @param mode - Thread safety mode for lazy initialization
74
* @param parameters - Optional parameters for dependency creation
75
* @return Lazy delegate for the nullable dependency
76
*/
77
inline fun <reified T> KoinComponent.injectOrNull(
78
qualifier: Qualifier? = null,
79
mode: LazyThreadSafetyMode = LazyThreadSafetyMode.SYNCHRONIZED,
80
noinline parameters: ParametersDefinition? = null
81
): Lazy<T?>
82
```
83
84
**Usage Examples:**
85
86
```kotlin
87
import org.koin.core.component.KoinComponent
88
import org.koin.core.component.inject
89
import org.koin.core.component.injectOrNull
90
import org.koin.core.qualifier.named
91
92
class OrderService : KoinComponent {
93
// Basic lazy injection
94
private val userService: UserService by inject()
95
96
// Injection with qualifier
97
private val primaryDb: Database by inject(named("primary"))
98
private val cacheDb: Database by inject(named("cache"))
99
100
// Injection with parameters
101
private val apiClient: ApiClient by inject {
102
parametersOf("https://api.example.com", 30)
103
}
104
105
// Nullable injection
106
private val optionalService: OptionalService? by injectOrNull()
107
108
// Non-synchronized lazy injection for performance
109
private val logger: Logger by inject(mode = LazyThreadSafetyMode.NONE)
110
111
fun processOrder(orderId: String) {
112
logger.info("Processing order $orderId")
113
val user = userService.findById(orderId)
114
// Dependencies resolved on first access
115
}
116
}
117
```
118
119
### Direct Dependency Retrieval
120
121
Get dependencies immediately without lazy initialization.
122
123
```kotlin { .api }
124
/**
125
* Get dependency directly from container
126
* @param qualifier - Optional qualifier to distinguish instances
127
* @param parameters - Optional parameters for dependency creation
128
* @return Resolved dependency instance
129
*/
130
inline fun <reified T> KoinComponent.get(
131
qualifier: Qualifier? = null,
132
noinline parameters: ParametersDefinition? = null
133
): T
134
135
/**
136
* Get dependency with nullable result
137
* @param qualifier - Optional qualifier to distinguish instances
138
* @param parameters - Optional parameters for dependency creation
139
* @return Resolved dependency instance or null if not found
140
*/
141
inline fun <reified T> KoinComponent.getOrNull(
142
qualifier: Qualifier? = null,
143
noinline parameters: ParametersDefinition? = null
144
): T?
145
146
/**
147
* Get all instances of a given type
148
* @return List of all resolved instances
149
*/
150
inline fun <reified T> KoinComponent.getAll(): List<T>
151
```
152
153
**Usage Examples:**
154
155
```kotlin
156
import org.koin.core.component.KoinComponent
157
import org.koin.core.component.get
158
import org.koin.core.component.getOrNull
159
import org.koin.core.component.getAll
160
import org.koin.core.qualifier.named
161
162
class ServiceManager : KoinComponent {
163
164
fun initializeServices() {
165
// Direct retrieval
166
val logger = get<Logger>()
167
logger.info("Initializing services")
168
169
// Retrieval with qualifier
170
val primaryDb = get<Database>(named("primary"))
171
val cacheDb = get<Database>(named("cache"))
172
173
// Retrieval with parameters
174
val httpClient = get<HttpClient> {
175
parametersOf("https://api.example.com", timeout = 30)
176
}
177
178
// Nullable retrieval
179
val optionalService = getOrNull<OptionalService>()
180
optionalService?.initialize()
181
182
// Get all instances
183
val allValidators = getAll<Validator>()
184
allValidators.forEach { it.configure() }
185
}
186
}
187
```
188
189
### Property Injection
190
191
Inject dependencies into mutable properties.
192
193
```kotlin { .api }
194
/**
195
* Inject dependency into mutable property
196
* @param qualifier - Optional qualifier to distinguish instances
197
* @param parameters - Optional parameters for dependency creation
198
*/
199
fun <T> KMutableProperty0<T>.inject(
200
qualifier: Qualifier? = null,
201
parameters: ParametersDefinition? = null
202
)
203
204
/**
205
* Inject dependency into mutable property using specific Koin instance
206
* @param koin - Koin instance to use for injection
207
* @param qualifier - Optional qualifier to distinguish instances
208
* @param parameters - Optional parameters for dependency creation
209
*/
210
fun <T> KMutableProperty0<T>.inject(
211
koin: Koin,
212
qualifier: Qualifier? = null,
213
parameters: ParametersDefinition? = null
214
)
215
216
/**
217
* Inject dependency into mutable property using specific scope
218
* @param scope - Scope to use for injection
219
* @param qualifier - Optional qualifier to distinguish instances
220
* @param parameters - Optional parameters for dependency creation
221
*/
222
fun <T> KMutableProperty0<T>.inject(
223
scope: Scope,
224
qualifier: Qualifier? = null,
225
parameters: ParametersDefinition? = null
226
)
227
```
228
229
**Usage Examples:**
230
231
```kotlin
232
import org.koin.ext.inject
233
import org.koin.core.component.KoinComponent
234
235
class ConfigurableService : KoinComponent {
236
// Mutable properties for injection
237
lateinit var logger: Logger
238
lateinit var database: Database
239
240
fun configure() {
241
// Inject into properties
242
::logger.inject()
243
::database.inject(named("primary"))
244
245
// Now properties are initialized
246
logger.info("Service configured")
247
}
248
}
249
250
// Standalone property injection
251
class GlobalConfig {
252
lateinit var appSettings: AppSettings
253
254
fun initialize(koin: Koin) {
255
::appSettings.inject(koin)
256
}
257
}
258
```
259
260
### KoinScopeComponent Interface
261
262
Component interface for classes that work with specific scopes.
263
264
```kotlin { .api }
265
/**
266
* Scoped component interface extending KoinComponent
267
* Provides direct access to a specific scope
268
*/
269
interface KoinScopeComponent : KoinComponent {
270
/**
271
* The scope associated with this component
272
*/
273
val scope: Scope
274
}
275
```
276
277
**Usage Examples:**
278
279
```kotlin
280
import org.koin.core.component.KoinScopeComponent
281
import org.koin.core.scope.Scope
282
import org.koin.core.qualifier.named
283
284
class UserSessionComponent(override val scope: Scope) : KoinScopeComponent {
285
// Inject from component's scope
286
private val userPreferences: UserPreferences by scope.inject()
287
private val sessionData: SessionData by scope.inject()
288
289
fun getUserData(): UserData {
290
return UserData(
291
preferences = userPreferences,
292
session = sessionData
293
)
294
}
295
}
296
297
// Scope creation and component usage
298
class UserController : KoinComponent {
299
fun createUserSession(userId: String): UserSessionComponent {
300
val userScope = getKoin().createScope(userId, named<UserScope>())
301
return UserSessionComponent(userScope)
302
}
303
}
304
```
305
306
### Scope Extension Functions
307
308
Extension functions for creating and managing component scopes.
309
310
```kotlin { .api }
311
/**
312
* Create a new scope for the component
313
* @param scopeId - Unique identifier for the scope
314
* @param qualifier - Scope qualifier/type
315
* @return New scope instance
316
*/
317
fun KoinScopeComponent.createScope(
318
scopeId: String = generateId(),
319
qualifier: Qualifier
320
): Scope
321
322
/**
323
* Get existing scope or null
324
* @param scopeId - Scope identifier
325
* @param qualifier - Scope qualifier/type
326
* @return Existing scope or null
327
*/
328
fun KoinScopeComponent.getScopeOrNull(
329
scopeId: String,
330
qualifier: Qualifier
331
): Scope?
332
333
/**
334
* Create scope lazily
335
* @param scopeId - Scope identifier
336
* @param qualifier - Scope qualifier/type
337
* @return Lazy delegate for scope
338
*/
339
fun KoinScopeComponent.newScope(
340
scopeId: String = generateId(),
341
qualifier: Qualifier
342
): Lazy<Scope>
343
344
/**
345
* Get existing scope or create new one
346
* @param scopeId - Scope identifier
347
* @param qualifier - Scope qualifier/type
348
* @return Existing or new scope
349
*/
350
fun KoinScopeComponent.getOrCreateScope(
351
scopeId: String = generateId(),
352
qualifier: Qualifier
353
): Scope
354
```
355
356
**Usage Examples:**
357
358
```kotlin
359
import org.koin.core.component.KoinScopeComponent
360
import org.koin.core.component.createScope
361
import org.koin.core.component.getOrCreateScope
362
import org.koin.core.qualifier.named
363
364
class FeatureComponent : KoinScopeComponent {
365
// Lazy scope creation
366
override val scope: Scope by newScope(qualifier = named<FeatureScope>())
367
368
// Alternative: explicit scope management
369
private val featureScope = createScope("feature-123", named<FeatureScope>())
370
371
fun processFeature() {
372
// Use scoped dependencies
373
val processor = scope.get<FeatureProcessor>()
374
processor.process()
375
}
376
377
fun cleanup() {
378
scope.close()
379
}
380
}
381
```
382
383
## Types
384
385
```kotlin { .api }
386
typealias ParametersDefinition = () -> ParametersHolder
387
388
class Koin {
389
inline fun <reified T> inject(
390
qualifier: Qualifier? = null,
391
mode: LazyThreadSafetyMode = LazyThreadSafetyMode.SYNCHRONIZED,
392
noinline parameters: ParametersDefinition? = null
393
): Lazy<T>
394
395
inline fun <reified T> get(
396
qualifier: Qualifier? = null,
397
noinline parameters: ParametersDefinition? = null
398
): T
399
400
fun createScope(scopeId: String, qualifier: Qualifier): Scope
401
fun getScope(scopeId: String): Scope
402
fun deleteScope(scopeId: String)
403
fun close()
404
}
405
406
enum class LazyThreadSafetyMode {
407
SYNCHRONIZED, PUBLICATION, NONE
408
}
409
```