CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-io-insert-koin--koin-core-js

KOIN - Kotlin simple Dependency Injection Framework for JavaScript/Browser platform

Pending
Overview
Eval results
Files

context-management.mddocs/

Context and Global Management

Application-wide context management for accessing the DI container across your application with global and custom context implementations.

Capabilities

Global Context Access

Access the Koin container globally throughout your JavaScript application.

/**
 * Global context singleton for JavaScript environments
 * Provides application-wide access to Koin container
 */
const GlobalContext: KoinContext;

interface KoinContext {
  /**
   * Get current Koin instance
   * @returns Current Koin instance or null if not started
   */
  get(): Koin | null;

  /**
   * Get current Koin instance or throw if not started
   * @returns Current Koin instance
   * @throws IllegalStateException if Koin not started
   */
  getOrNull(): Koin | null;

  /**
   * Start Koin with pre-configured application
   * @param koinApplication - Configured KoinApplication instance
   * @returns Started KoinApplication
   */
  startKoin(koinApplication: KoinApplication): KoinApplication;

  /**
   * Stop Koin and cleanup all resources
   * Closes all scopes and clears global state
   */
  stopKoin(): void;

  /**
   * Load additional modules into running application
   * @param modules - Modules to load dynamically
   */
  loadKoinModules(modules: Module[]): void;

  /**
   * Load single module into running application
   * @param module - Single module to load
   */
  loadKoinModules(module: Module): void;

  /**
   * Unload modules from running application
   * @param modules - Modules to unload
   */
  unloadKoinModules(modules: Module[]): void;

  /**
   * Unload single module from running application
   * @param module - Module to unload
   */
  unloadKoinModules(module: Module): void;
}

Usage Examples:

import { GlobalContext, startKoin, module } from "koin-core";

// Start Koin globally
const appModule = module((builder) => {
  builder.single(() => new DatabaseService());
  builder.factory(() => new ApiClient());
});

startKoin((app) => {
  app.modules([appModule]);
  app.printLogger();
});

// Access global Koin instance anywhere in application
function useDatabase() {
  const koin = GlobalContext.get();
  if (koin) {
    const database = koin.get(); // DatabaseService
    return database.query("SELECT * FROM users");
  }
  throw new Error("Koin not initialized");
}

// Safe access with null check
function safeApiCall() {
  const koin = GlobalContext.getOrNull();
  if (koin) {
    const apiClient = koin.get(); // ApiClient
    return apiClient.fetchData();
  }
  console.warn("Koin not available, using fallback");
  return fallbackApiCall();
}

// Stop global Koin
function shutdown() {
  GlobalContext.stopKoin();
}

Dynamic Module Management

Load and unload modules at runtime for dynamic application configuration.

/**
 * Load additional modules into running Koin application
 * @param modules - Array of modules to load
 */
function loadKoinModules(modules: Module[]): void;

/**
 * Load single module into running application
 * @param module - Module to load
 */
function loadKoinModules(module: Module): void;

/**
 * Unload modules from running application
 * @param modules - Array of modules to unload  
 */
function unloadKoinModules(modules: Module[]): void;

/**
 * Unload single module from running application
 * @param module - Module to unload
 */
function unloadKoinModules(module: Module): void;

Usage Examples:

import { 
  startKoin, 
  loadKoinModules, 
  unloadKoinModules, 
  module,
  GlobalContext 
} from "koin-core";

// Start with core modules
const coreModule = module((builder) => {
  builder.single(() => new ConfigService());
  builder.single(() => new Logger());
});

startKoin((app) => {
  app.modules([coreModule]);
});

// Load feature modules dynamically
const featureModule = module((builder) => {
  builder.single(() => new FeatureService());
  builder.factory(() => new FeatureHandler());
});

const analyticsModule = module((builder) => {
  builder.single(() => new AnalyticsService());
  builder.factory(() => new EventTracker());
});

// Load modules at runtime
loadKoinModules([featureModule, analyticsModule]);

// Use dynamically loaded dependencies  
const koin = GlobalContext.get();
const featureService = koin.get(); // FeatureService
const analytics = koin.get(); // AnalyticsService

// Later, unload modules when no longer needed
unloadKoinModules([analyticsModule]);
unloadKoinModules(featureModule); // Single module variant

Context State Management

Manage Koin application state and lifecycle through the context.

interface KoinContext {
  /**
   * Check if Koin is currently started
   * @returns true if Koin application is running
   */
  isStarted(): boolean;

  /**
   * Get current application state
   * @returns KoinApplication instance if started
   */
  getKoinApplication(): KoinApplication | null;
}

Usage Examples:

import { GlobalContext, startKoin, stopKoin } from "koin-core";

class ApplicationManager {
  async initialize() {
    if (!GlobalContext.isStarted()) {
      console.log("Starting Koin...");
      
      startKoin((app) => {
        app.modules([coreModule, apiModule]);
        app.printLogger();
      });
      
      console.log("Koin started successfully");
    } else {
      console.log("Koin already running");
    }
  }
  
  async shutdown() {
    if (GlobalContext.isStarted()) {
      console.log("Stopping Koin...");
      stopKoin();
      console.log("Koin stopped");
    }
  }
  
  getApplicationInfo() {
    const app = GlobalContext.getKoinApplication();
    if (app) {
      return {
        isRunning: true,
        koinInstance: app.koin,
        moduleCount: app.koin.getAllScopes().length
      };
    }
    return { isRunning: false };
  }
}

const appManager = new ApplicationManager();
await appManager.initialize();

// Check application status
const info = appManager.getApplicationInfo();
console.log(`Koin running: ${info.isRunning}`);

Custom Context Implementation

Create custom context implementations for specific environments or use cases.

/**
 * Create custom Koin context for specific environments
 */
class CustomKoinContext implements KoinContext {
  constructor() {
    this._koin = null;
    this._application = null;
  }
  
  get(): Koin | null {
    return this._koin;
  }
  
  getOrNull(): Koin | null {
    return this._koin;
  }
  
  startKoin(koinApplication: KoinApplication): KoinApplication {
    if (this._koin) {
      throw new KoinApplicationAlreadyStartedException("Koin already started");
    }
    
    this._application = koinApplication;
    this._koin = koinApplication.koin;
    return koinApplication;
  }
  
  stopKoin(): void {
    if (this._application) {
      this._application.close();
      this._application = null;
      this._koin = null;
    }
  }
  
  loadKoinModules(modules: Module[]): void {
    if (this._koin) {
      this._koin.loadModules(modules);
    }
  }
  
  unloadKoinModules(modules: Module[]): void {
    if (this._koin) {
      this._koin.unloadModules(modules);
    }
  }
}

Usage Examples:

import { KoinContext, koinApplication, module } from "koin-core";

// Create isolated context for testing
const testContext = new CustomKoinContext();

const testModule = module((builder) => {
  builder.single(() => new MockDatabaseService());
  builder.factory(() => new TestApiClient());
});

// Use custom context
const testApp = koinApplication((app) => {
  app.modules([testModule]);
  app.allowOverride(true);
});

testContext.startKoin(testApp);

// Test with isolated context
function runTests() {
  const koin = testContext.get();
  const mockDb = koin.get(); // MockDatabaseService
  
  // Run tests with mock dependencies
  assert(mockDb instanceof MockDatabaseService);
  
  // Cleanup test context
  testContext.stopKoin();
}

// Context for specific environments
class BrowserContext extends CustomKoinContext {
  startKoin(koinApplication) {
    console.log("Starting Koin in browser environment");
    // Browser-specific initialization
    window.koinContext = this;
    return super.startKoin(koinApplication);
  }
  
  stopKoin() {
    console.log("Stopping Koin in browser environment");
    delete window.koinContext;
    super.stopKoin();
  }
}

class NodeContext extends CustomKoinContext {
  startKoin(koinApplication) {
    console.log("Starting Koin in Node.js environment");
    // Node.js-specific initialization
    global.koinContext = this;
    return super.startKoin(koinApplication);
  }
  
  stopKoin() {
    console.log("Stopping Koin in Node.js environment"); 
    delete global.koinContext;
    super.stopKoin();
  }
}

Environment-Specific Context Usage

Use different context strategies for different JavaScript environments.

/**
 * Platform-specific context detection and usage
 */
function getPlatformContext(): KoinContext {
  if (typeof window !== 'undefined') {
    // Browser environment
    return new BrowserContext();
  } else if (typeof global !== 'undefined') {
    // Node.js environment
    return new NodeContext();
  } else {
    // Default/unknown environment
    return GlobalContext;
  }
}

Usage Examples:

import { getPlatformContext, koinApplication, module } from "koin-core";

// Platform-agnostic application setup
class Application {
  constructor() {
    this.context = getPlatformContext();
  }
  
  async start() {
    const appModule = module((builder) => {
      if (typeof window !== 'undefined') {
        // Browser-specific dependencies
        builder.single(() => new BrowserStorageService());
        builder.single(() => new DOMLogger());
      } else {
        // Node.js-specific dependencies  
        builder.single(() => new FileStorageService());
        builder.single(() => new ConsoleLogger());
      }
      
      // Common dependencies
      builder.factory(() => new ApiClient());
      builder.single(() => new ConfigService());
    });
    
    const app = koinApplication((app) => {
      app.modules([appModule]);
      app.printLogger();
    });
    
    this.context.startKoin(app);
    console.log("Application started with platform-specific context");
  }
  
  async stop() {
    this.context.stopKoin();
    console.log("Application stopped");
  }
  
  getService(type) {
    const koin = this.context.get();
    return koin ? koin.get(type) : null;
  }
}

// Usage
const app = new Application();
await app.start();

// Get platform-appropriate services
const storage = app.getService("storage"); // BrowserStorage or FileStorage
const logger = app.getService("logger");   // DOMLogger or ConsoleLogger

await app.stop();

Types

/** Context interface for Koin container management */
interface KoinContext {
  get(): Koin | null;
  getOrNull(): Koin | null;
  startKoin(koinApplication: KoinApplication): KoinApplication;
  stopKoin(): void;
  loadKoinModules(modules: Module[]): void;
  loadKoinModules(module: Module): void;
  unloadKoinModules(modules: Module[]): void;
  unloadKoinModules(module: Module): void;
  isStarted(): boolean;
  getKoinApplication(): KoinApplication | null;
}

/** Global context singleton */
const GlobalContext: KoinContext;

/** Exception thrown when Koin application is already started */
class KoinApplicationAlreadyStartedException extends Error {
  constructor(message: string);
}

/** Exception thrown when trying to access Koin before it's started */
class IllegalStateException extends Error {
  constructor(message: string);
}

Install with Tessl CLI

npx tessl i tessl/maven-io-insert-koin--koin-core-js

docs

application-startup.md

context-management.md

dependency-injection.md

error-handling.md

index.md

logging-system.md

module-system.md

qualifiers-parameters.md

scoping-lifecycle.md

tile.json