v0.4.0 on Maven Central

kotlin-container

Lightweight dependency injection for Kotlin. Auto-resolution, scoped lifecycles, thread safety — no code generation, no annotations, zero configuration.

implementation("com.cristianllanos:container:0.4.0")

Features

Quick Start

Concrete classes resolve automatically — no registration needed.

kotlin
class Logger
class UserRepository(val logger: Logger)
class UserService(val repo: UserRepository)

val container = Container()
val service = container.resolve<UserService>()
// resolves Logger → UserRepository → UserService automatically

Bindings

Use factory, singleton, or scoped when you need explicit control.

kotlin
val container = Container {
    // New instance every time
    factory<PaymentGateway> { StripeGateway() }

    // One instance forever
    singleton<NotificationService> { SlackNotificationService() }

    // One instance per scope
    scoped<DbConnection> { DbConnection(resolve<Config>()) }
}

// Auto-resolved registration (no lambda needed)
container.singleton<TenantService>()
container.factory<TempProcessor>()

Scoped Lifecycles

One instance per scope — shared within a context, isolated between contexts.

kotlin
container.scoped<DbConnection> { DbConnection() }
    .onClose { it.disconnect() }

container.scope { scope ->
    val db = scope.resolve<DbConnection>()   // created once
    scope.resolve<DbConnection>()            // same instance
}  // scope closes → db.disconnect() called

// Nested scopes cascade close (deepest first)
// AutoCloseable instances close automatically

Service Providers

Group related registrations. Parameters are auto-resolved from the container.

kotlin
class AuthServiceProvider {
    fun register(container: Container) {
        container.singleton<TokenStore> { RedisTokenStore() }
        container.singleton<AuthGuard> { AuthGuard(resolve<TokenStore>()) }
    }
}

class EventServiceProvider {
    fun register(subscriber: Subscriber) {  // auto-resolved!
        subscriber.subscribe<OrderPlaced>(
            InventoryListener::class,
            NotificationListener::class,
        )
    }
}

val container = Container()
container.register(AuthServiceProvider(), EventServiceProvider())

Learn

Get started in seconds

Add the dependency, create a container, and resolve. That's it.