4 of 5

Service Providers

Group related registrations into reusable, modular units.

Basic providers

Any class with a register() method works as a service provider. The simplest form takes the container as a parameter:

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

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

Auto-resolved parameters

Providers can ask for any dependency, not just the container — parameters are auto-resolved:

kotlin
class OrderEventProvider {
    fun register(subscriber: Subscriber) {
        subscriber.subscribe<OrderPlaced>(
            InventoryListener::class,
            NotificationListener::class,
        )
    }
}

// The container resolves Subscriber automatically
container.register(OrderEventProvider())

This keeps providers decoupled from the container itself. They only depend on the interfaces they actually need.

Registering multiple providers

Pass multiple providers in one call for a clean bootstrap:

kotlin
val container = Container()
container.register(
    AuthServiceProvider(),
    PaymentServiceProvider(),
    EventServiceProvider(),
    NotificationServiceProvider(),
)

Scope providers

Providers work with scopes to set up contextual environments. Define what each scope context needs:

kotlin
class RequestScopeProvider(private val request: HttpRequest) {
    fun register(container: Container) {
        container.singleton<RequestId> { RequestId(request.id) }
        container.singleton<CurrentUser> { CurrentUser(request.userId) }
        container.scoped<DbTransaction> { DbTransaction(resolve<DataSource>()) }
            .onClose { it.rollbackIfOpen() }
    }
}

// Use with the shorthand extension
container.scope(RequestScopeProvider(request)) { scope ->
    scope.resolve<RequestHandler>().handle()
}

Next steps

Explore advanced features like thread safety, callable injection, and interface segregation.