or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application.mdcomponents.mdindex.mdmodule-dsl.mdscopes.md

application.mddocs/

0

# Application Configuration

1

2

The `KoinApplication` class is the main entry point for configuring and starting a Koin dependency injection container. It provides a fluent API for setting up modules, properties, logging, and other application-wide configuration.

3

4

## KoinApplication Creation

5

6

```kotlin { .api }

7

fun koinApplication(

8

createEagerInstances: Boolean = true,

9

appDeclaration: KoinAppDeclaration? = null

10

): KoinApplication

11

12

fun koinApplication(appDeclaration: KoinAppDeclaration?): KoinApplication

13

fun koinApplication(configuration: KoinConfiguration?): KoinApplication

14

fun koinApplication(createEagerInstances: Boolean): KoinApplication

15

16

typealias KoinAppDeclaration = KoinApplication.() -> Unit

17

```

18

19

The `koinApplication` function creates a new `KoinApplication` instance with optional configuration.

20

21

### Basic Usage

22

23

```kotlin

24

val app = koinApplication {

25

modules(listOf(appModule, networkModule))

26

properties(mapOf("api.url" to "https://api.example.com"))

27

logger(PrintLogger())

28

}

29

```

30

31

## KoinApplication Configuration

32

33

```kotlin { .api }

34

class KoinApplication {

35

val koin: Koin

36

37

fun modules(modules: Module): KoinApplication

38

fun modules(vararg modules: Module): KoinApplication

39

fun modules(modules: List<Module>): KoinApplication

40

41

fun properties(values: Map<String, Any>): KoinApplication

42

fun fileProperties(fileName: String = "/koin.properties"): KoinApplication

43

fun environmentProperties(): KoinApplication

44

45

fun logger(logger: Logger): KoinApplication

46

47

fun createEagerInstances()

48

fun allowOverride(override: Boolean)

49

50

fun close()

51

}

52

```

53

54

### Module Loading

55

56

Load dependency injection modules into the application:

57

58

```kotlin

59

val databaseModule = module {

60

single<Database> { DatabaseImpl() }

61

}

62

63

val serviceModule = module {

64

single<UserService> { UserServiceImpl(get()) }

65

}

66

67

val app = koinApplication {

68

// Single module

69

modules(databaseModule)

70

71

// Multiple modules with vararg

72

modules(databaseModule, serviceModule)

73

74

// List of modules

75

modules(listOf(databaseModule, serviceModule))

76

}

77

```

78

79

### Property Configuration

80

81

```kotlin

82

val app = koinApplication {

83

// Map of properties

84

properties(mapOf(

85

"database.url" to "jdbc:h2:mem:test",

86

"api.timeout" to 30,

87

"feature.enabled" to true

88

))

89

90

// Load from file (platform-specific)

91

fileProperties("/config/app.properties")

92

93

// Load from environment variables

94

environmentProperties()

95

}

96

97

// Access properties in definitions

98

val appModule = module {

99

single<DatabaseConfig> {

100

DatabaseConfig(

101

url = getProperty<String>("database.url"),

102

timeout = getProperty<Int>("api.timeout")

103

)

104

}

105

}

106

```

107

108

### Logging Configuration

109

110

```kotlin { .api }

111

interface Logger {

112

fun display(level: Level, message: String)

113

fun isAt(level: Level): Boolean

114

}

115

116

enum class Level {

117

DEBUG, INFO, WARNING, ERROR, NONE

118

}

119

```

120

121

Set up logging to monitor Koin's behavior:

122

123

```kotlin

124

val app = koinApplication {

125

logger(PrintLogger(Level.DEBUG))

126

modules(appModule)

127

}

128

129

// Custom logger implementation

130

class CustomLogger : Logger {

131

override fun display(level: Level, message: String) {

132

println("[$level] $message")

133

}

134

135

override fun isAt(level: Level): Boolean = true

136

}

137

138

val appWithCustomLogger = koinApplication {

139

logger(CustomLogger())

140

modules(appModule)

141

}

142

```

143

144

### Eager Instance Creation

145

146

```kotlin

147

val app = koinApplication {

148

modules(appModule)

149

// Create all singleton instances marked with createdAtStart = true

150

createEagerInstances()

151

}

152

153

// In module definition

154

val eagerModule = module {

155

single<AppConfig>(createdAtStart = true) { AppConfigImpl() }

156

single<DatabaseConnection>(createdAtStart = true) { DatabaseConnectionImpl() }

157

}

158

```

159

160

### Definition Override

161

162

```kotlin

163

val app = koinApplication {

164

allowOverride(true) // Allow overriding existing definitions

165

modules(baseModule, overrideModule)

166

}

167

```

168

169

## Global Context Management

170

171

While `KoinApplication` creates isolated contexts, Koin also provides global context management for simpler usage patterns:

172

173

```kotlin { .api }

174

// Platform-specific functions (available on JVM/Android)

175

fun startKoin(appDeclaration: KoinAppDeclaration): KoinApplication

176

fun stopKoin()

177

178

// Context access

179

fun GlobalContext.get(): Koin

180

fun GlobalContext.getOrNull(): Koin?

181

```

182

183

### Global Context Usage

184

185

```kotlin

186

// Start global Koin context

187

startKoin {

188

modules(listOf(appModule, serviceModule))

189

logger(PrintLogger())

190

properties(mapOf("env" to "production"))

191

}

192

193

class MyService : KoinComponent {

194

// Uses global context automatically

195

private val repository: Repository by inject()

196

}

197

198

// Stop global context

199

stopKoin()

200

```

201

202

## Advanced Configuration

203

204

### Multiple Applications

205

206

```kotlin

207

class MultiAppExample {

208

fun setupApplications() {

209

// Separate application contexts

210

val webApp = koinApplication {

211

modules(webModule)

212

properties(mapOf("context" to "web"))

213

}

214

215

val backgroundApp = koinApplication {

216

modules(backgroundModule)

217

properties(mapOf("context" to "background"))

218

}

219

220

// Each has its own dependency graph

221

val webService = webApp.koin.get<WebService>()

222

val bgService = backgroundApp.koin.get<BackgroundService>()

223

}

224

}

225

```

226

227

### Dynamic Module Loading

228

229

```kotlin

230

class DynamicConfiguration {

231

fun configureDynamically() {

232

val app = koinApplication()

233

234

// Load base modules

235

app.modules(coreModule)

236

237

// Conditionally load additional modules

238

if (isWebEnvironment()) {

239

app.modules(webModule)

240

}

241

242

if (isDevelopment()) {

243

app.modules(debugModule)

244

app.logger(PrintLogger(Level.DEBUG))

245

}

246

247

app.createEagerInstances()

248

}

249

}

250

```

251

252

### Configuration from External Sources

253

254

```kotlin

255

class ExternalConfiguration {

256

fun loadFromConfig(configFile: String) {

257

val config = loadConfig(configFile)

258

259

val app = koinApplication {

260

// Dynamic module selection

261

modules(selectModules(config.features))

262

263

// Environment-specific properties

264

properties(config.properties)

265

266

// Conditional features

267

if (config.loggingEnabled) {

268

logger(PrintLogger(config.logLevel))

269

}

270

271

if (config.eagerLoading) {

272

createEagerInstances()

273

}

274

}

275

}

276

}

277

```

278

279

## Error Handling

280

281

```kotlin { .api }

282

class KoinApplicationAlreadyStartedException(message: String) : RuntimeException(message)

283

```

284

285

### Safe Application Management

286

287

```kotlin

288

class SafeApplicationManager {

289

private var currentApp: KoinApplication? = null

290

291

fun startSafely(config: KoinAppDeclaration): Boolean {

292

return try {

293

currentApp?.close()

294

currentApp = koinApplication(config)

295

true

296

} catch (e: Exception) {

297

println("Failed to start Koin application: ${e.message}")

298

false

299

}

300

}

301

302

fun stopSafely() {

303

currentApp?.close()

304

currentApp = null

305

}

306

}

307

```

308

309

## Testing Support

310

311

### Test Application Setup

312

313

```kotlin

314

class TestApplicationSetup {

315

lateinit var testApp: KoinApplication

316

317

@Before

318

fun setup() {

319

testApp = koinApplication {

320

modules(testModule)

321

properties(mapOf(

322

"database.url" to "jdbc:h2:mem:test",

323

"mock.services" to true

324

))

325

}

326

}

327

328

@After

329

fun teardown() {

330

testApp.close()

331

}

332

333

@Test

334

fun testWithKoin() {

335

val service = testApp.koin.get<UserService>()

336

// Test with injected dependencies

337

}

338

}

339

```

340

341

### Mock Module Override

342

343

```kotlin

344

val testModule = module {

345

single<UserRepository> { MockUserRepository() }

346

single<EmailService> { MockEmailService() }

347

}

348

349

val testApp = koinApplication {

350

allowOverride(true)

351

modules(productionModule, testModule) // testModule overrides production

352

}

353

```

354

355

## Performance Considerations

356

357

### Lazy vs Eager Loading

358

359

```kotlin

360

val optimizedApp = koinApplication {

361

modules(coreModule)

362

363

// Only create essential services eagerly

364

// Non-critical services remain lazy

365

createEagerInstances()

366

}

367

368

val coreModule = module {

369

// Critical services - created at startup

370

single<DatabaseConnection>(createdAtStart = true) {

371

DatabaseConnectionImpl()

372

}

373

374

// Non-critical services - created on demand

375

single<ReportGenerator> { ReportGeneratorImpl(get()) }

376

}

377

```

378

379

### Module Organization

380

381

```kotlin

382

// Organize modules by feature for better performance

383

val featureModules = listOf(

384

authenticationModule,

385

userManagementModule,

386

reportingModule

387

)

388

389

val app = koinApplication {

390

modules(coreModule) // Load core first

391

modules(featureModules) // Then features

392

}

393

```