0
# Context and Global Management
1
2
Application-wide context management for accessing the DI container across your application with global and custom context implementations.
3
4
## Capabilities
5
6
### Global Context Access
7
8
Access the Koin container globally throughout your JavaScript application.
9
10
```javascript { .api }
11
/**
12
* Global context singleton for JavaScript environments
13
* Provides application-wide access to Koin container
14
*/
15
const GlobalContext: KoinContext;
16
17
interface KoinContext {
18
/**
19
* Get current Koin instance
20
* @returns Current Koin instance or null if not started
21
*/
22
get(): Koin | null;
23
24
/**
25
* Get current Koin instance or throw if not started
26
* @returns Current Koin instance
27
* @throws IllegalStateException if Koin not started
28
*/
29
getOrNull(): Koin | null;
30
31
/**
32
* Start Koin with pre-configured application
33
* @param koinApplication - Configured KoinApplication instance
34
* @returns Started KoinApplication
35
*/
36
startKoin(koinApplication: KoinApplication): KoinApplication;
37
38
/**
39
* Stop Koin and cleanup all resources
40
* Closes all scopes and clears global state
41
*/
42
stopKoin(): void;
43
44
/**
45
* Load additional modules into running application
46
* @param modules - Modules to load dynamically
47
*/
48
loadKoinModules(modules: Module[]): void;
49
50
/**
51
* Load single module into running application
52
* @param module - Single module to load
53
*/
54
loadKoinModules(module: Module): void;
55
56
/**
57
* Unload modules from running application
58
* @param modules - Modules to unload
59
*/
60
unloadKoinModules(modules: Module[]): void;
61
62
/**
63
* Unload single module from running application
64
* @param module - Module to unload
65
*/
66
unloadKoinModules(module: Module): void;
67
}
68
```
69
70
**Usage Examples:**
71
72
```javascript
73
import { GlobalContext, startKoin, module } from "koin-core";
74
75
// Start Koin globally
76
const appModule = module((builder) => {
77
builder.single(() => new DatabaseService());
78
builder.factory(() => new ApiClient());
79
});
80
81
startKoin((app) => {
82
app.modules([appModule]);
83
app.printLogger();
84
});
85
86
// Access global Koin instance anywhere in application
87
function useDatabase() {
88
const koin = GlobalContext.get();
89
if (koin) {
90
const database = koin.get(); // DatabaseService
91
return database.query("SELECT * FROM users");
92
}
93
throw new Error("Koin not initialized");
94
}
95
96
// Safe access with null check
97
function safeApiCall() {
98
const koin = GlobalContext.getOrNull();
99
if (koin) {
100
const apiClient = koin.get(); // ApiClient
101
return apiClient.fetchData();
102
}
103
console.warn("Koin not available, using fallback");
104
return fallbackApiCall();
105
}
106
107
// Stop global Koin
108
function shutdown() {
109
GlobalContext.stopKoin();
110
}
111
```
112
113
### Dynamic Module Management
114
115
Load and unload modules at runtime for dynamic application configuration.
116
117
```javascript { .api }
118
/**
119
* Load additional modules into running Koin application
120
* @param modules - Array of modules to load
121
*/
122
function loadKoinModules(modules: Module[]): void;
123
124
/**
125
* Load single module into running application
126
* @param module - Module to load
127
*/
128
function loadKoinModules(module: Module): void;
129
130
/**
131
* Unload modules from running application
132
* @param modules - Array of modules to unload
133
*/
134
function unloadKoinModules(modules: Module[]): void;
135
136
/**
137
* Unload single module from running application
138
* @param module - Module to unload
139
*/
140
function unloadKoinModules(module: Module): void;
141
```
142
143
**Usage Examples:**
144
145
```javascript
146
import {
147
startKoin,
148
loadKoinModules,
149
unloadKoinModules,
150
module,
151
GlobalContext
152
} from "koin-core";
153
154
// Start with core modules
155
const coreModule = module((builder) => {
156
builder.single(() => new ConfigService());
157
builder.single(() => new Logger());
158
});
159
160
startKoin((app) => {
161
app.modules([coreModule]);
162
});
163
164
// Load feature modules dynamically
165
const featureModule = module((builder) => {
166
builder.single(() => new FeatureService());
167
builder.factory(() => new FeatureHandler());
168
});
169
170
const analyticsModule = module((builder) => {
171
builder.single(() => new AnalyticsService());
172
builder.factory(() => new EventTracker());
173
});
174
175
// Load modules at runtime
176
loadKoinModules([featureModule, analyticsModule]);
177
178
// Use dynamically loaded dependencies
179
const koin = GlobalContext.get();
180
const featureService = koin.get(); // FeatureService
181
const analytics = koin.get(); // AnalyticsService
182
183
// Later, unload modules when no longer needed
184
unloadKoinModules([analyticsModule]);
185
unloadKoinModules(featureModule); // Single module variant
186
```
187
188
### Context State Management
189
190
Manage Koin application state and lifecycle through the context.
191
192
```javascript { .api }
193
interface KoinContext {
194
/**
195
* Check if Koin is currently started
196
* @returns true if Koin application is running
197
*/
198
isStarted(): boolean;
199
200
/**
201
* Get current application state
202
* @returns KoinApplication instance if started
203
*/
204
getKoinApplication(): KoinApplication | null;
205
}
206
```
207
208
**Usage Examples:**
209
210
```javascript
211
import { GlobalContext, startKoin, stopKoin } from "koin-core";
212
213
class ApplicationManager {
214
async initialize() {
215
if (!GlobalContext.isStarted()) {
216
console.log("Starting Koin...");
217
218
startKoin((app) => {
219
app.modules([coreModule, apiModule]);
220
app.printLogger();
221
});
222
223
console.log("Koin started successfully");
224
} else {
225
console.log("Koin already running");
226
}
227
}
228
229
async shutdown() {
230
if (GlobalContext.isStarted()) {
231
console.log("Stopping Koin...");
232
stopKoin();
233
console.log("Koin stopped");
234
}
235
}
236
237
getApplicationInfo() {
238
const app = GlobalContext.getKoinApplication();
239
if (app) {
240
return {
241
isRunning: true,
242
koinInstance: app.koin,
243
moduleCount: app.koin.getAllScopes().length
244
};
245
}
246
return { isRunning: false };
247
}
248
}
249
250
const appManager = new ApplicationManager();
251
await appManager.initialize();
252
253
// Check application status
254
const info = appManager.getApplicationInfo();
255
console.log(`Koin running: ${info.isRunning}`);
256
```
257
258
### Custom Context Implementation
259
260
Create custom context implementations for specific environments or use cases.
261
262
```javascript { .api }
263
/**
264
* Create custom Koin context for specific environments
265
*/
266
class CustomKoinContext implements KoinContext {
267
constructor() {
268
this._koin = null;
269
this._application = null;
270
}
271
272
get(): Koin | null {
273
return this._koin;
274
}
275
276
getOrNull(): Koin | null {
277
return this._koin;
278
}
279
280
startKoin(koinApplication: KoinApplication): KoinApplication {
281
if (this._koin) {
282
throw new KoinApplicationAlreadyStartedException("Koin already started");
283
}
284
285
this._application = koinApplication;
286
this._koin = koinApplication.koin;
287
return koinApplication;
288
}
289
290
stopKoin(): void {
291
if (this._application) {
292
this._application.close();
293
this._application = null;
294
this._koin = null;
295
}
296
}
297
298
loadKoinModules(modules: Module[]): void {
299
if (this._koin) {
300
this._koin.loadModules(modules);
301
}
302
}
303
304
unloadKoinModules(modules: Module[]): void {
305
if (this._koin) {
306
this._koin.unloadModules(modules);
307
}
308
}
309
}
310
```
311
312
**Usage Examples:**
313
314
```javascript
315
import { KoinContext, koinApplication, module } from "koin-core";
316
317
// Create isolated context for testing
318
const testContext = new CustomKoinContext();
319
320
const testModule = module((builder) => {
321
builder.single(() => new MockDatabaseService());
322
builder.factory(() => new TestApiClient());
323
});
324
325
// Use custom context
326
const testApp = koinApplication((app) => {
327
app.modules([testModule]);
328
app.allowOverride(true);
329
});
330
331
testContext.startKoin(testApp);
332
333
// Test with isolated context
334
function runTests() {
335
const koin = testContext.get();
336
const mockDb = koin.get(); // MockDatabaseService
337
338
// Run tests with mock dependencies
339
assert(mockDb instanceof MockDatabaseService);
340
341
// Cleanup test context
342
testContext.stopKoin();
343
}
344
345
// Context for specific environments
346
class BrowserContext extends CustomKoinContext {
347
startKoin(koinApplication) {
348
console.log("Starting Koin in browser environment");
349
// Browser-specific initialization
350
window.koinContext = this;
351
return super.startKoin(koinApplication);
352
}
353
354
stopKoin() {
355
console.log("Stopping Koin in browser environment");
356
delete window.koinContext;
357
super.stopKoin();
358
}
359
}
360
361
class NodeContext extends CustomKoinContext {
362
startKoin(koinApplication) {
363
console.log("Starting Koin in Node.js environment");
364
// Node.js-specific initialization
365
global.koinContext = this;
366
return super.startKoin(koinApplication);
367
}
368
369
stopKoin() {
370
console.log("Stopping Koin in Node.js environment");
371
delete global.koinContext;
372
super.stopKoin();
373
}
374
}
375
```
376
377
### Environment-Specific Context Usage
378
379
Use different context strategies for different JavaScript environments.
380
381
```javascript { .api }
382
/**
383
* Platform-specific context detection and usage
384
*/
385
function getPlatformContext(): KoinContext {
386
if (typeof window !== 'undefined') {
387
// Browser environment
388
return new BrowserContext();
389
} else if (typeof global !== 'undefined') {
390
// Node.js environment
391
return new NodeContext();
392
} else {
393
// Default/unknown environment
394
return GlobalContext;
395
}
396
}
397
```
398
399
**Usage Examples:**
400
401
```javascript
402
import { getPlatformContext, koinApplication, module } from "koin-core";
403
404
// Platform-agnostic application setup
405
class Application {
406
constructor() {
407
this.context = getPlatformContext();
408
}
409
410
async start() {
411
const appModule = module((builder) => {
412
if (typeof window !== 'undefined') {
413
// Browser-specific dependencies
414
builder.single(() => new BrowserStorageService());
415
builder.single(() => new DOMLogger());
416
} else {
417
// Node.js-specific dependencies
418
builder.single(() => new FileStorageService());
419
builder.single(() => new ConsoleLogger());
420
}
421
422
// Common dependencies
423
builder.factory(() => new ApiClient());
424
builder.single(() => new ConfigService());
425
});
426
427
const app = koinApplication((app) => {
428
app.modules([appModule]);
429
app.printLogger();
430
});
431
432
this.context.startKoin(app);
433
console.log("Application started with platform-specific context");
434
}
435
436
async stop() {
437
this.context.stopKoin();
438
console.log("Application stopped");
439
}
440
441
getService(type) {
442
const koin = this.context.get();
443
return koin ? koin.get(type) : null;
444
}
445
}
446
447
// Usage
448
const app = new Application();
449
await app.start();
450
451
// Get platform-appropriate services
452
const storage = app.getService("storage"); // BrowserStorage or FileStorage
453
const logger = app.getService("logger"); // DOMLogger or ConsoleLogger
454
455
await app.stop();
456
```
457
458
## Types
459
460
```javascript { .api }
461
/** Context interface for Koin container management */
462
interface KoinContext {
463
get(): Koin | null;
464
getOrNull(): Koin | null;
465
startKoin(koinApplication: KoinApplication): KoinApplication;
466
stopKoin(): void;
467
loadKoinModules(modules: Module[]): void;
468
loadKoinModules(module: Module): void;
469
unloadKoinModules(modules: Module[]): void;
470
unloadKoinModules(module: Module): void;
471
isStarted(): boolean;
472
getKoinApplication(): KoinApplication | null;
473
}
474
475
/** Global context singleton */
476
const GlobalContext: KoinContext;
477
478
/** Exception thrown when Koin application is already started */
479
class KoinApplicationAlreadyStartedException extends Error {
480
constructor(message: string);
481
}
482
483
/** Exception thrown when trying to access Koin before it's started */
484
class IllegalStateException extends Error {
485
constructor(message: string);
486
}
487
```