0
# Global Context
1
2
Application-wide dependency management with convenient global functions for common operations.
3
4
## Capabilities
5
6
### Application Lifecycle
7
8
Global functions for starting and stopping the Koin application.
9
10
```kotlin { .api }
11
/**
12
* Start a global Koin application with an existing KoinApplication
13
* @param koinApplication - Pre-configured KoinApplication instance
14
* @return The started KoinApplication
15
*/
16
fun startKoin(koinApplication: KoinApplication): KoinApplication
17
18
/**
19
* Start a global Koin application with DSL configuration
20
* @param appDeclaration - DSL configuration block
21
* @return The started KoinApplication
22
*/
23
fun startKoin(appDeclaration: KoinAppDeclaration): KoinApplication
24
25
/**
26
* Stop the global Koin application and cleanup all resources
27
*/
28
fun stopKoin()
29
```
30
31
**Usage Examples:**
32
33
```kotlin
34
import org.koin.core.context.startKoin
35
import org.koin.core.context.stopKoin
36
import org.koin.dsl.module
37
38
// Define application modules
39
val networkModule = module {
40
single { HttpClient() }
41
single { ApiService(get()) }
42
}
43
44
val dataModule = module {
45
single { UserRepository(get()) }
46
single { ConfigService() }
47
}
48
49
// Start Koin with DSL
50
startKoin {
51
modules(networkModule, dataModule)
52
printLogger()
53
properties(mapOf(
54
"api.baseUrl" to "https://api.example.com",
55
"app.version" to "1.0.0"
56
))
57
}
58
59
// Application code can now use global Koin...
60
61
// Stop Koin when application shuts down
62
Runtime.getRuntime().addShutdownHook(Thread {
63
stopKoin()
64
})
65
```
66
67
### Dynamic Module Management
68
69
Global functions for loading and unloading modules at runtime.
70
71
```kotlin { .api }
72
/**
73
* Load a single module into the global Koin context
74
* @param module - Module to load
75
*/
76
fun loadKoinModules(module: Module)
77
78
/**
79
* Load multiple modules into the global Koin context
80
* @param modules - List of modules to load
81
*/
82
fun loadKoinModules(modules: List<Module>)
83
84
/**
85
* Unload a single module from the global Koin context
86
* @param module - Module to unload
87
*/
88
fun unloadKoinModules(module: Module)
89
90
/**
91
* Unload multiple modules from the global Koin context
92
* @param modules - List of modules to unload
93
*/
94
fun unloadKoinModules(modules: List<Module>)
95
```
96
97
**Usage Examples:**
98
99
```kotlin
100
import org.koin.core.context.*
101
import org.koin.dsl.module
102
103
// Base application modules
104
val coreModule = module {
105
single { DatabaseClient() }
106
single { ConfigService() }
107
}
108
109
val apiModule = module {
110
single { ApiClient(get<ConfigService>().apiUrl) }
111
}
112
113
// Start with core modules
114
startKoin {
115
modules(coreModule)
116
}
117
118
// Load additional modules based on environment
119
val environment = System.getProperty("app.environment", "production")
120
121
when (environment) {
122
"development" -> {
123
val devModule = module {
124
single<Logger> { ConsoleLogger() }
125
single { MockApiService() }
126
}
127
loadKoinModules(devModule)
128
}
129
"test" -> {
130
val testModule = module {
131
single<Logger> { TestLogger() }
132
single { MockDatabaseClient() }
133
}
134
loadKoinModules(testModule)
135
}
136
else -> {
137
val prodModule = module {
138
single<Logger> { FileLogger("/var/log/app.log") }
139
}
140
loadKoinModules(listOf(apiModule, prodModule))
141
}
142
}
143
144
// Later, unload test modules when switching environments
145
if (environment == "test") {
146
unloadKoinModules(testModule)
147
loadKoinModules(apiModule)
148
}
149
```
150
151
### Global Dependency Access
152
153
Direct access to the global Koin container for dependency resolution.
154
155
```kotlin { .api }
156
/**
157
* Get the global Koin instance
158
* @return Global Koin container
159
* @throws KoinApplicationNotStartedException if Koin hasn't been started
160
*/
161
fun GlobalContext.get(): Koin
162
163
/**
164
* Get the global Koin instance or null if not started
165
* @return Global Koin container or null
166
*/
167
fun GlobalContext.getOrNull(): Koin?
168
```
169
170
**Usage Examples:**
171
172
```kotlin
173
import org.koin.core.context.GlobalContext
174
175
// Access global Koin directly
176
val koin = GlobalContext.get()
177
val userService = koin.get<UserService>()
178
179
// Safe access to global Koin
180
val koinOrNull = GlobalContext.getOrNull()
181
if (koinOrNull != null) {
182
val configService = koinOrNull.get<ConfigService>()
183
println("App version: ${configService.getVersion()}")
184
} else {
185
println("Koin not started yet")
186
}
187
188
// Use in utility functions
189
object ServiceLocator {
190
fun getUserService(): UserService? {
191
return GlobalContext.getOrNull()?.getOrNull<UserService>()
192
}
193
194
fun getConfigValue(key: String, default: String = ""): String {
195
return GlobalContext.getOrNull()?.getProperty(key, default) ?: default
196
}
197
}
198
199
// Usage
200
val userService = ServiceLocator.getUserService()
201
val dbUrl = ServiceLocator.getConfigValue("db.url", "localhost:5432")
202
```
203
204
205
### Global Context Patterns
206
207
Common patterns for using global context effectively.
208
209
**Application Bootstrap Pattern:**
210
211
```kotlin
212
class Application {
213
companion object {
214
fun start() {
215
startKoin {
216
modules(getAllModules())
217
printLogger(Level.INFO)
218
properties(loadProperties())
219
}
220
221
println("Application started with Koin")
222
}
223
224
fun stop() {
225
println("Shutting down application...")
226
stopKoin()
227
println("Application stopped")
228
}
229
230
private fun getAllModules(): List<Module> {
231
return listOf(
232
coreModule,
233
serviceModule,
234
repositoryModule,
235
controllerModule
236
)
237
}
238
239
private fun loadProperties(): Map<String, Any> {
240
return mapOf(
241
"app.name" to "MyApp",
242
"app.version" to "1.0.0",
243
"db.url" to (System.getenv("DB_URL") ?: "localhost:5432")
244
)
245
}
246
}
247
}
248
249
// Usage
250
fun main() {
251
Application.start()
252
253
// Application logic...
254
255
Runtime.getRuntime().addShutdownHook(Thread {
256
Application.stop()
257
})
258
}
259
```
260
261
**Feature Toggle Pattern:**
262
263
```kotlin
264
object FeatureManager {
265
private val featureModules = mutableMapOf<String, Module>()
266
267
fun registerFeature(name: String, module: Module) {
268
featureModules[name] = module
269
}
270
271
fun enableFeature(name: String) {
272
featureModules[name]?.let { module ->
273
loadKoinModules(module)
274
println("Enabled feature: $name")
275
}
276
}
277
278
fun disableFeature(name: String) {
279
featureModules[name]?.let { module ->
280
unloadKoinModules(module)
281
println("Disabled feature: $name")
282
}
283
}
284
285
fun isFeatureEnabled(name: String): Boolean {
286
return featureModules[name]?.isLoaded == true
287
}
288
}
289
290
// Register features
291
val analyticsModule = module {
292
single { AnalyticsService() }
293
single { EventTracker() }
294
}
295
296
val experimentModule = module {
297
single { ExperimentService() }
298
single { ABTestManager() }
299
}
300
301
FeatureManager.registerFeature("analytics", analyticsModule)
302
FeatureManager.registerFeature("experiments", experimentModule)
303
304
// Enable features based on configuration
305
val enabledFeatures = getConfigValue("enabled.features", "").split(",")
306
enabledFeatures.forEach { feature ->
307
FeatureManager.enableFeature(feature.trim())
308
}
309
```
310
311
**Environment-Specific Configuration Pattern:**
312
313
```kotlin
314
object EnvironmentConfig {
315
fun configureForEnvironment(env: String) {
316
when (env.lowercase()) {
317
"development" -> configureDevelopment()
318
"staging" -> configureStaging()
319
"production" -> configureProduction()
320
else -> throw IllegalArgumentException("Unknown environment: $env")
321
}
322
}
323
324
private fun configureDevelopment() {
325
val devModule = module {
326
single<Logger> { ConsoleLogger(Level.DEBUG) }
327
single<DatabaseClient> { H2DatabaseClient() }
328
single<ApiClient> { MockApiClient() }
329
}
330
331
loadKoinModules(devModule)
332
}
333
334
private fun configureStaging() {
335
val stagingModule = module {
336
single<Logger> { FileLogger("staging.log", Level.INFO) }
337
single<DatabaseClient> { PostgresDatabaseClient(getProperty("staging.db.url")) }
338
single<ApiClient> { HttpApiClient(getProperty("staging.api.url")) }
339
}
340
341
loadKoinModules(stagingModule)
342
}
343
344
private fun configureProduction() {
345
val prodModule = module {
346
single<Logger> { CloudLogger(Level.WARN) }
347
single<DatabaseClient> { PostgresDatabaseClient(getProperty("prod.db.url")) }
348
single<ApiClient> { HttpApiClient(getProperty("prod.api.url")) }
349
}
350
351
loadKoinModules(prodModule)
352
}
353
}
354
355
// Usage in application startup
356
fun main() {
357
startKoin {
358
modules(coreModule)
359
}
360
361
val environment = System.getenv("APP_ENV") ?: "development"
362
EnvironmentConfig.configureForEnvironment(environment)
363
364
// Application runs with environment-specific configuration
365
}
366
```
367
368
## Type Definitions
369
370
```kotlin { .api }
371
/**
372
* Interface for global context implementations
373
*/
374
interface KoinContext {
375
fun get(): Koin
376
fun getOrNull(): Koin?
377
fun stopKoin()
378
fun startKoin(koinApplication: KoinApplication): KoinApplication
379
fun startKoin(appDeclaration: KoinAppDeclaration): KoinApplication
380
fun loadKoinModules(module: Module, createEagerInstances: Boolean = false)
381
fun loadKoinModules(modules: List<Module>, createEagerInstances: Boolean = false)
382
fun unloadKoinModules(module: Module)
383
fun unloadKoinModules(modules: List<Module>)
384
}
385
386
/**
387
* Exception thrown when trying to access Koin before it's started
388
*/
389
class KoinApplicationNotStartedException : RuntimeException("KoinApplication has not been started")
390
391
/**
392
* Exception thrown when trying to start Koin when it's already started
393
*/
394
class KoinApplicationAlreadyStartedException : RuntimeException("KoinApplication has already been started")
395
```