CtrlK
BlogDocsLog inGet started
Tessl Logo

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

Core dependency injection framework for Kotlin Multiplatform projects targeting WebAssembly JavaScript environments

Pending
Overview
Eval results
Files

dependency-injection.mddocs/

Dependency Injection

Core dependency injection functionality for resolving and managing object instances.

Capabilities

Instance Resolution

Core methods for retrieving dependencies from the Koin container.

/**
 * Get a dependency instance immediately
 * @param qualifier - Optional qualifier to distinguish multiple instances
 * @param parameters - Optional parameters to pass to the factory function
 * @return Instance of the requested type
 * @throws NoDefinitionFoundException if no definition is found
 */
inline fun <reified T : Any> Koin.get(qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null): T

/**
 * Get a dependency instance or null if not found
 * @param qualifier - Optional qualifier to distinguish multiple instances
 * @param parameters - Optional parameters to pass to the factory function
 * @return Instance of the requested type or null
 */
inline fun <reified T : Any> Koin.getOrNull(qualifier: Qualifier? = null, noinline parameters: ParametersDefinition? = null): T?

/**
 * Get a dependency instance by class
 * @param clazz - Class type to resolve
 * @param qualifier - Optional qualifier
 * @param parameters - Optional parameters
 * @return Instance of the requested type
 */
fun <T> Koin.get(clazz: KClass<*>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null): T

/**
 * Get a dependency instance by class or null if not found
 * @param clazz - Class type to resolve
 * @param qualifier - Optional qualifier
 * @param parameters - Optional parameters
 * @return Instance of the requested type or null
 */
fun <T> Koin.getOrNull(clazz: KClass<*>, qualifier: Qualifier? = null, parameters: ParametersDefinition? = null): T?

Usage Examples:

import org.koin.core.context.startKoin
import org.koin.core.parameter.parametersOf
import org.koin.core.qualifier.named
import org.koin.dsl.module

// Service definitions
class UserService(private val apiKey: String)
class DatabaseClient
class EmailService

val appModule = module {
    single { DatabaseClient() }
    single(named("primary")) { EmailService() }
    factory { (apiKey: String) -> UserService(apiKey) }
}

startKoin { modules(appModule) }

// Get instances
val database = koin.get<DatabaseClient>()
val emailService = koin.get<EmailService>(named("primary"))
val userService = koin.get<UserService> { parametersOf("api-key-123") }

// Safe resolution
val optionalService = koin.getOrNull<SomeOptionalService>()

Lazy Injection

Lazy dependency resolution for deferred initialization.

/**
 * Get a lazy dependency that will be resolved on first access
 * @param qualifier - Optional qualifier to distinguish multiple instances
 * @param mode - Thread safety mode for the lazy delegate
 * @param parameters - Optional parameters to pass to the factory function
 * @return Lazy delegate that resolves the dependency on first access
 */
inline fun <reified T : Any> Koin.inject(qualifier: Qualifier? = null, mode: LazyThreadSafetyMode = KoinPlatformTools.defaultLazyMode(), noinline parameters: ParametersDefinition? = null): Lazy<T>

/**
 * Get a lazy dependency that may be null
 * @param qualifier - Optional qualifier to distinguish multiple instances
 * @param mode - Thread safety mode for the lazy delegate
 * @param parameters - Optional parameters to pass to the factory function
 * @return Lazy delegate that resolves the dependency or null on first access
 */
inline fun <reified T : Any> Koin.injectOrNull(qualifier: Qualifier? = null, mode: LazyThreadSafetyMode = KoinPlatformTools.defaultLazyMode(), noinline parameters: ParametersDefinition? = null): Lazy<T?>

Usage Examples:

import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import org.koin.core.parameter.parametersOf

class UserController : KoinComponent {
    // Lazy injection - resolved on first access
    private val userService: UserService by inject()
    private val emailService: EmailService by inject(named("primary"))
    
    // Lazy injection with parameters
    private val apiClient: ApiClient by inject { parametersOf("endpoint.url") }
    
    // Optional lazy injection
    private val optionalService: OptionalService? by injectOrNull()
    
    fun handleRequest() {
        // Services are resolved here on first access
        val user = userService.getCurrentUser()
        emailService.sendWelcome(user)
    }
}

Multiple Instances

Retrieve all instances of a given type.

/**
 * Get all instances of a given type
 * @return List of all instances matching the type
 */
inline fun <reified T> Koin.getAll(): List<T>

/**
 * Get all instances of a given class
 * @param clazz - Class type to resolve
 * @return List of all instances matching the class
 */
fun <T> Koin.getAll(clazz: KClass<*>): List<T>

Usage Examples:

import org.koin.dsl.module
import org.koin.core.qualifier.named

interface NotificationProvider
class EmailNotificationProvider : NotificationProvider
class SmsNotificationProvider : NotificationProvider
class PushNotificationProvider : NotificationProvider

val notificationModule = module {
    single<NotificationProvider>(named("email")) { EmailNotificationProvider() }
    single<NotificationProvider>(named("sms")) { SmsNotificationProvider() }
    single<NotificationProvider>(named("push")) { PushNotificationProvider() }
}

// Get all notification providers
val allProviders = koin.getAll<NotificationProvider>()
println("Found ${allProviders.size} notification providers")

Runtime Declaration

Declare instances at runtime for dynamic dependency registration.

/**
 * Declare an instance at runtime
 * @param instance - Instance to declare
 * @param qualifier - Optional qualifier
 * @param secondaryTypes - Additional types this instance can be resolved as
 * @param allowOverride - Whether to allow overriding existing definitions
 */
inline fun <reified T> Koin.declare(instance: T, qualifier: Qualifier? = null, secondaryTypes: List<KClass<*>> = emptyList(), allowOverride: Boolean = true)

Usage Examples:

import org.koin.core.qualifier.named

// Dynamically declare instances
val dynamicConfig = ConfigurationService("production")
koin.declare(dynamicConfig, named("runtime"))

// Declare with additional types
interface Logger
class FileLogger : Logger
val logger = FileLogger()
koin.declare(logger, secondaryTypes = listOf(Logger::class))

// Later retrieve the declared instances
val config = koin.get<ConfigurationService>(named("runtime"))
val loggerInstance = koin.get<Logger>()

Property Management

Manage application properties within the Koin container.

/**
 * Get a property value with a default fallback
 * @param key - Property key
 * @param defaultValue - Default value if property is not found
 * @return Property value or default value
 */
fun <T : Any> Koin.getProperty(key: String, defaultValue: T): T

/**
 * Get a property value or null if not found
 * @param key - Property key
 * @return Property value or null
 */
fun <T : Any> Koin.getProperty(key: String): T?

/**
 * Set a property value
 * @param key - Property key
 * @param value - Property value
 */
fun Koin.setProperty(key: String, value: Any)

/**
 * Delete a property
 * @param key - Property key to delete
 */
fun Koin.deleteProperty(key: String)

Usage Examples:

import org.koin.dsl.module

// Use properties in module definitions
val configModule = module {
    single { DatabaseClient(getProperty("db.url", "localhost:5432")) }
    single { ApiClient(getProperty<String>("api.endpoint")) }
}

// Set properties at runtime
koin.setProperty("feature.enabled", true)
koin.setProperty("max.connections", 100)

// Use properties in code
val isFeatureEnabled = koin.getProperty("feature.enabled", false)
val maxConnections = koin.getProperty<Int>("max.connections")

// Check if property exists
val optionalSetting = koin.getProperty<String>("optional.setting")
if (optionalSetting != null) {
    println("Optional setting: $optionalSetting")
}

// Delete properties
koin.deleteProperty("temporary.flag")

Module Management

Load and unload modules dynamically at runtime.

/**
 * Load modules into the container
 * @param modules - List of modules to load
 * @param allowOverride - Whether to allow overriding existing definitions
 * @param createEagerInstances - Whether to create eager instances immediately
 */
fun Koin.loadModules(modules: List<Module>, allowOverride: Boolean = true, createEagerInstances: Boolean = false)

/**
 * Unload modules from the container
 * @param modules - List of modules to unload
 */
fun Koin.unloadModules(modules: List<Module>)

/**
 * Create all eager instances
 */
fun Koin.createEagerInstances()

Usage Examples:

import org.koin.dsl.module

// Define modules
val testModule = module {
    single { TestService() }
}

val productionModule = module {
    single { ProductionService() }
}

// Load modules dynamically
when (environment) {
    "test" -> koin.loadModules(listOf(testModule))
    "production" -> koin.loadModules(listOf(productionModule), createEagerInstances = true)
}

// Later unload test modules
if (environment != "test") {
    koin.unloadModules(listOf(testModule))
}

// Manually trigger eager instance creation
koin.createEagerInstances()

Container Lifecycle

Manage the Koin container lifecycle.

/**
 * Close the Koin container and cleanup all resources
 */
fun Koin.close()

Usage Examples:

// Close container when application shuts down
Runtime.getRuntime().addShutdownHook(Thread {
    koin.close()
})

Type Definitions

/**
 * Type alias for parameter definition functions
 */
typealias ParametersDefinition = () -> ParametersHolder

/**
 * Container for dependency injection parameters
 */
class ParametersHolder {
    /** List of parameter values */
    val values: List<Any?>
    
    /** Whether to use indexed parameter access */
    val useIndexedValues: Boolean?
    
    /** Get parameter by index */
    operator fun <T> get(i: Int): T
    
    /** Set parameter by index */
    fun <T> set(i: Int, t: T)
    
    /** Get parameter by type */
    inline fun <reified T : Any> get(): T
    
    /** Get optional parameter by type */
    inline fun <reified T : Any> getOrNull(): T?
    
    /** Parameter count */
    fun size(): Int
    
    /** Check if empty */
    fun isEmpty(): Boolean
    
    /** Check if not empty */
    fun isNotEmpty(): Boolean
}

/**
 * Create parameter holder from values
 * @param parameters - Variable number of parameter values
 * @return ParametersHolder containing the parameters
 */
fun parametersOf(vararg parameters: Any?): ParametersHolder

/**
 * Create empty parameter holder
 * @return Empty ParametersHolder
 */
fun emptyParametersHolder(): ParametersHolder

Install with Tessl CLI

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

docs

application.md

components.md

dependency-injection.md

global-context.md

index.md

modules.md

scopes.md

tile.json