### Hilt Network Module Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/hilt-migration.md Example of a Hilt network module setup using `@Module`, `@Provides`, and `@Singleton` annotations to provide OkHttpClient, Retrofit, and ApiService. ```kotlin @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .build() } @Provides @Singleton fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl("https://api.example.com") .client(okHttpClient) .build() } @Provides @Singleton fun provideApiService(retrofit: Retrofit): ApiService { return retrofit.create(ApiService::class.java) } } ``` -------------------------------- ### Use typed startup APIs Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/starting-koin.md Examples of starting Koin using the typed API provided by the compiler plugin. ```kotlin // Simple startup startKoin() // With additional configuration startKoin { printLogger() } // Isolated instance val myKoin = koinApplication().koin // Configuration for Compose/Ktor val config = koinConfiguration() ``` -------------------------------- ### Initialize multi-module projects Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/starting-koin.md Example of starting Koin in a project with multiple modules using the compiler plugin. ```kotlin // feature/src/main/kotlin/FeatureModule.kt @Module @Configuration @ComponentScan("com.myapp.feature") class FeatureModule // app/src/main/kotlin/MyApp.kt @KoinApplication class MyApp // Start Koin startKoin() ``` -------------------------------- ### Complete Koin Application Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/dsl.md A comprehensive example of setting up Koin, including configuring logging, loading environment properties, declaring multiple modules, and creating eager singletons. ```kotlin startKoin { // Configure logging logger(Level.INFO) // Load properties environmentProperties() // Declare modules modules( networkModule, databaseModule, repositoryModule, viewModelModule ) // Create eager singletons createEagerInstances() } ``` -------------------------------- ### Complete KoinIsolated Implementation Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-ktor/ktor-isolated.md A full example showing module definition, plugin installation, and dependency injection within the application scope. ```kotlin val appModule = module { singleOf(::UserRepository) singleOf(::UserService) requestScope { scopedOf(::RequestLogger) } } fun Application.main() { // Install Koin in isolated mode install(KoinIsolated) { slf4jLogger() modules(appModule) } // Injection works within Application scope val userService by inject() routing { get("/users/{id}") { val logger = call.scope.get() val id = call.parameters["id"]!! logger.log("Fetching user $id") val user = userService.getUser(id) call.respond(user) } } } ``` -------------------------------- ### Migration: Before (Hilt) Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/jsr330.md Example of dependency injection setup using Hilt before migrating to Koin. ```kotlin @HiltAndroidApp class MyApplication : Application() @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var analytics: Analytics } @Singleton class Analytics @Inject constructor( @ApplicationContext private val context: Context ) @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideRetrofit(): Retrofit = Retrofit.Builder() .baseUrl("https://api.example.com") .build() } ``` -------------------------------- ### Start Koin and Inject Services in Ktor Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/ktor.md Install the Koin module and inject services lazily. This setup is typically done within the Ktor Application's main function. ```kotlin fun Application.main() { // Install Koin install(Koin) { modules(appModule) } // Lazy inject UserService val service by inject() service.loadUsers() // Routing section routing { get("/hello") { val userName = call.queryParameters["name"] ?: "Alice" val user = service.getUserOrNull(userName) val message = service.prepareHelloMessage(user) call.respondText(message) } } } ``` -------------------------------- ### Koin Dependency Injection Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/intro/what-is-dependency-injection.md Demonstrates how to define dependencies using Koin's DSL and start Koin in an Android application. This approach automates dependency resolution and lifecycle management. ```kotlin // Define dependencies once val appModule = module { single() single() single() single() single() viewModel() } // Start Koin once class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { modules(appModule) } } } // Use anywhere - Koin handles the entire dependency graph class MainActivity : AppCompatActivity() { private val viewModel: UserViewModel by viewModel() // That's it! Koin creates UserViewModel and all its dependencies } ``` -------------------------------- ### Start Koin Application Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/kotlin.md Initialize Koin and retrieve the main application instance. ```kotlin val appModule = module { single() single() bind UserRepository::class single() bind UserService::class } fun main() { startKoin { modules(appModule) } val userApplication = KoinPlatform.getKoin().get() userApplication.sayHello("Alice") } ``` -------------------------------- ### Start Koin Application Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-annotations/modules.md Start Koin globally using the typed API, optionally with a configuration block for logger setup. ```kotlin fun main() { startKoin() // Or with configuration startKoin { printLogger() } } ``` -------------------------------- ### Start Koin with Annotations Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/compiler-plugin.md Use typed APIs with annotations to start Koin without generating code. This example shows starting Koin globally with an application class and an optional configuration block. ```kotlin @KoinApplication @ComponentScan("com.myapp") class MyApp // Start Koin with typed API startKoin() // Or with additional configuration startKoin { androidContext(this@MyApplication) printLogger() } ``` -------------------------------- ### Multi-Module Application Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/intro/koin-vs-hilt.md Koin auto-discovers modules annotated with @Configuration and @ComponentScan. Hilt requires manual installation of each module using @InstallIn. ```kotlin // feature/auth/AuthModule.kt @Module @ComponentScan @Configuration // Auto-discovered! class AuthModule // feature/profile/ProfileModule.kt @Module @ComponentScan @Configuration // Auto-discovered! class ProfileModule // app/MyApp.kt @KoinApplication // No need to list modules class MyApp ``` ```kotlin // feature/auth/AuthModule.kt @Module @InstallIn(SingletonComponent::class) class AuthModule { ... } // feature/profile/ProfileModule.kt @Module @InstallIn(SingletonComponent::class) class ProfileModule { ... } // app/MyApp.kt @HiltAndroidApp class MyApp // Still need correct @InstallIn everywhere ``` -------------------------------- ### Setup Koin for Ktor Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/gradle.md Configure dependencies and install Koin in a Ktor server application. ```kotlin dependencies { implementation(platform("io.insert-koin:koin-bom:$koin_version")) implementation("io.insert-koin:koin-ktor") implementation("io.insert-koin:koin-logger-slf4j") } ``` ```kotlin fun Application.module() { install(Koin) { slf4jLogger() modules(appModule) } } ``` -------------------------------- ### Koin Startup - Before KSP Source: https://github.com/insertkoinio/koin/blob/main/docs/migration/from-ksp-to-compiler-plugin.md Example of Koin startup using generated .module extensions from KSP. ```kotlin import org.koin.ksp.generated. // Generated extensions @Module @ComponentScan("com.myapp") class AppModule fun main() { startKoin { modules(AppModule().module) // Generated .module extension } } ``` -------------------------------- ### Install Koin Plugin Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-ktor/ktor.md Initialize Koin within the Ktor Application module. ```kotlin fun Application.main() { install(Koin) { slf4jLogger() modules(appModule) } } ``` -------------------------------- ### Koin Startup - After Compiler Plugin Source: https://github.com/insertkoinio/koin/blob/main/docs/migration/from-ksp-to-compiler-plugin.md Example of Koin startup using the typed API with @KoinApplication. ```kotlin // No generated imports needed @Module @ComponentScan("com.myapp") class AppModule @KoinApplication(modules = [AppModule::class]) class MyApp fun main() { startKoin() // Typed API } ``` -------------------------------- ### Complete ResolutionExtension example Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/extension-manager.md A full example demonstrating custom resolution logic using ResolutionExtension. ```kotlin @OptIn(KoinExperimentalAPI::class) fun resolutionExtensionExample() { val resolutionExtension = object : ResolutionExtension { val instanceMap = mapOf, Any>( ComponentA::class to ComponentA() ) override val name: String = "custom-resolver" override fun resolve( scope: Scope, instanceContext: ResolutionContext ): Any? { return instanceMap[instanceContext.clazz] } } val koin = koinApplication { printLogger(Level.DEBUG) koin.addResolutionExtension(resolutionExtension) modules(module { // ComponentB depends on ComponentA // ComponentA will be resolved from the extension single { ComponentB(get()) } }) }.koin val componentB = koin.get() // componentB.a is the instance from resolutionExtension } ``` -------------------------------- ### Complete Ktor and Koin Test Example Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-ktor/ktor-testing.md Use this example to test Ktor applications integrated with Koin. It sets up an isolated Koin context and mocks dependencies for reliable testing. Ensure KoinIsolated is installed and routing is configured. ```kotlin class UserApiTest : KoinTest { @Test fun `should return all users`() = testApplication { application { install(KoinIsolated) { modules(testModule) } routing { val userService by inject() get("/api/users") { call.respond(userService.getAllUsers()) } } } client.get("/api/users").apply { assertEquals(HttpStatusCode.OK, status) val users = Json.decodeFromString>(bodyAsText()) assertEquals(2, users.size) } } @Test fun `should return user by id`() = testApplication { application { install(KoinIsolated) { modules(testModule) } routing { val userService by inject() get("/api/users/{id}") { val id = call.parameters["id"]!! val user = userService.getUser(id) ?: return@get call.respond(HttpStatusCode.NotFound) call.respond(user) } } } client.get("/api/users/1").apply { assertEquals(HttpStatusCode.OK, status) } client.get("/api/users/999").apply { assertEquals(HttpStatusCode.NotFound, status) } } } val testModule = module { single { MockUserRepository( listOf( User("1", "Alice", "alice@example.com"), User("2", "Bob", "bob@example.com") ) ) } singleOf(::UserService) } ``` -------------------------------- ### Install Koin and Inject Services in Ktor Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/ktor-annotations.md Installs Koin with generated configuration and demonstrates lazy injection of a UserService. The routing section defines a '/hello' endpoint. ```kotlin fun Application.main() { // Install Koin with generated configuration install(Koin) { slf4jLogger() withConfiguration() } // Lazy inject UserService val service by inject() service.loadUsers() // Routing section routing { get("/hello") { val userName = call.queryParameters["name"] ?: "Alice" val user = service.getUserOrNull(userName) val message = service.prepareHelloMessage(user) call.respondText(message) } } } ``` -------------------------------- ### Migration: After (Koin with JSR-330) Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/jsr330.md Example of dependency injection setup after migrating to Koin, retaining JSR-330 annotations where applicable. ```kotlin // Application - use startKoin class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@MyApplication) modules(appModule) } } } // Activity - use by inject() class MainActivity : AppCompatActivity() { private val analytics: Analytics by inject() } // Keep @Singleton and @Inject unchanged! @Singleton class Analytics @Inject constructor( private val context: Context // Koin provides Context automatically ) // Module with @Single for provided instances @Module @ComponentScan class NetworkModule { @Single fun provideRetrofit(): Retrofit = Retrofit.Builder() .baseUrl("https://api.example.com") .build() } ``` -------------------------------- ### Start Koin globally Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/starting-koin.md Standard approach for initializing Koin in a main function. ```kotlin fun main() { startKoin { modules(appModule) } // Use anywhere val service: MyService = get() } ``` -------------------------------- ### Hilt Application Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/hilt-migration.md Basic Hilt application setup using the `@HiltAndroidApp` annotation. ```kotlin @HiltAndroidApp class MyApplication : Application() ``` -------------------------------- ### Complete Koin Compiler Plugin Configuration Example Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-annotations/options.md A complete example of configuring the Koin compiler plugin in build.gradle.kts, demonstrating all available options with their typical settings. ```kotlin // build.gradle.kts plugins { alias(libs.plugins.koin.compiler) } koinCompiler { userLogs = true // Log component detection debugLogs = false // Verbose logs (off by default) compileSafety = true // Compile-time dependency validation strictSafety = true // Force aggregator to re-run safety pass (auto-detected by default) skipDefaultValues = true // Use Kotlin defaults instead of DI resolution unsafeDslChecks = true // Validate DSL usage } ``` -------------------------------- ### Koin Application - Custom Configuration Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-annotations/annotations-inventory.md Starts a Koin application with custom configuration options. Allows for additional setup like logging or specific Koin configurations. ```kotlin MyApp.startKoin { printLogger() // additional configuration } ``` -------------------------------- ### Initialize Koin with Annotations Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/start.md Using Koin Annotations to start the application with specific module configurations. ```kotlin @KoinApplication class MainApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@MainApplication) } } } ``` ```kotlin @Module @Configuration @ComponentScan("com.myapp.data") class DataModule @Module @Configuration @ComponentScan("com.myapp.domain") class DomainModule @KoinApplication class MainApplication // Start with multiple modules startKoin { androidLogger() androidContext(this@MainApplication) } ``` -------------------------------- ### Setup Koin for Kotlin/JVM Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/gradle.md Configure dependencies and initialize Koin in a pure Kotlin application. ```kotlin dependencies { implementation(platform("io.insert-koin:koin-bom:$koin_version")) implementation("io.insert-koin:koin-core") } ``` ```kotlin fun main() { startKoin { modules(appModule) } } ``` ```kotlin dependencies { testImplementation("io.insert-koin:koin-test") testImplementation("io.insert-koin:koin-test-junit5") // or junit4 } ``` -------------------------------- ### Koin Compiler Plugin DSL Example Source: https://github.com/insertkoinio/koin/blob/main/docs/intro/index.md This snippet demonstrates defining dependencies using Koin's Compiler Plugin DSL. It shows how to declare singletons and view models. Ensure Koin is started with the defined modules. ```kotlin class UserRepository(private val api: ApiService) class UserViewModel(private val repository: UserRepository) : ViewModel() val appModule = module { single() single() viewModel() } startKoin { modules(appModule) } class MainActivity : AppCompatActivity() { private val viewModel: UserViewModel by viewModel() } ``` -------------------------------- ### Start Koin and Use Component Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/koin-component.md Initialize Koin with your modules and then create a component that utilizes Koin for dependency injection. ```kotlin // Start Koin fun main() { startKoin { modules(myModule) } // Create component that uses Koin MyComponent() } ``` -------------------------------- ### Start Koin with DSL Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/modules-android.md Initializes Koin using the standard DSL, including logger configuration and module registration. ```kotlin class MainApplication : Application() { override fun onCreate() { super.onCreate() startKoin { // Android logger androidLogger() // or with level androidLogger(Level.DEBUG) // Android context androidContext(this@MainApplication) // Modules modules(appModule, networkModule, dataModule) } } } ``` -------------------------------- ### Configure Room Database with Koin Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/binding-patterns.md Demonstrates database module setup using Koin DSL or Annotations. ```kotlin @Database(entities = [User::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao } fun createDatabase(context: Context): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app-database").build() fun createUserDao(database: AppDatabase): UserDao = database.userDao() val databaseModule = module { single { create(::createDatabase) } single { create(::createUserDao) } } ``` ```kotlin @Module class DatabaseModule { @Single fun provideDatabase(context: Context): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app-database").build() @Single fun provideUserDao(database: AppDatabase): UserDao = database.userDao() } ``` -------------------------------- ### Starting Koin with @KoinApplication Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-annotations/start.md Use the @KoinApplication annotation on a class to define the entry point for Koin startup, specifying modules to load. ```kotlin @KoinApplication(modules = [AppModule::class]) class MyApp fun main() { startKoin { printLogger() } // Use your Koin API as usual KoinPlatform.getKoin().get() } ``` -------------------------------- ### Start Koin Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/why.md Initialize the Koin container by passing the defined modules to the startKoin function. ```kotlin fun main() { // Just start Koin startKoin { modules(myModule) } } ``` -------------------------------- ### Start Koin in Application Entry Point Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/kotlin-annotations.md Initializes Koin using the generated startKoin function and retrieves a dependency instance. ```kotlin fun main() { KoinUserApplication.startKoin() val userApplication = KoinPlatform.getKoin().get() userApplication.sayHello("Alice") } ``` -------------------------------- ### Declare a Singleton with Creation at Start Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-annotations/annotations-inventory.md Use @Single with 'createdAtStart = true' to ensure the singleton instance is created when Koin starts, rather than on first request. ```kotlin @Single(createdAtStart = true) class MyClass(val d : MyDependency) ``` -------------------------------- ### Create a custom KoinExtension Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/extension-manager.md Example implementation of a custom extension class. ```kotlin class MyCustomExtension : KoinExtension { private lateinit var koin: Koin override fun onRegister(koin: Koin) { this.koin = koin // Initialize your extension } override fun onClose() { // Cleanup resources } fun doSomething() { // Your extension logic } } ``` -------------------------------- ### Start Ktor Embedded Server Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/ktor.md This snippet shows how to start a Ktor embedded server using Netty on a specified port and run the main Ktor application. ```kotlin fun main(args: Array) { embeddedServer(Netty, port = 8080) { main() }.start(wait = true) } ``` -------------------------------- ### Compose-Managed Koin Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-compose/compose.md Use KoinApplication composable to let Compose manage Koin setup automatically. This simplifies setup by handling Android Context injection and lifecycle management. ```kotlin @Composable fun App() { KoinApplication(configuration = koinConfiguration { modules(appModule) }) { MyScreen() } } ``` -------------------------------- ### Initialize Koin in KMP or Non-Android Source: https://github.com/insertkoinio/koin/blob/main/projects/llms.txt Start Koin for Kotlin Multiplatform or non-Android environments. ```kotlin import org.koin.core.context.startKoin startKoin { modules(commonModule, platformModule) } ``` -------------------------------- ### Setup Koin for Android Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/gradle.md Configure dependencies and initialize Koin in an Android Application class. ```kotlin dependencies { implementation(platform("io.insert-koin:koin-bom:$koin_version")) implementation("io.insert-koin:koin-android") } ``` ```kotlin class MainApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@MainApplication) modules(appModule) } } } ``` ```kotlin dependencies { // Jetpack WorkManager implementation("io.insert-koin:koin-androidx-workmanager") // Navigation Graph implementation("io.insert-koin:koin-androidx-navigation") // AndroidX Startup implementation("io.insert-koin:koin-androidx-startup") // Java Compatibility implementation("io.insert-koin:koin-android-compat") } ``` -------------------------------- ### Define Koin Modules and Application Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/hilt-migration.md Demonstrates declaring feature modules and initializing Koin in the Android Application class. ```kotlin // :feature:home module val homeModule = module { viewModel { HomeViewModel(get()) } factory { HomeRepository(get()) } } // :app module class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@MyApplication) modules( coreModule, dataModule, homeModule, // Feature module profileModule // Another feature module ) } } } ``` -------------------------------- ### Setup Koin for Kotlin Multiplatform Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/gradle.md Configure dependencies in the shared module's build.gradle.kts. ```kotlin kotlin { sourceSets { commonMain.dependencies { implementation(platform("io.insert-koin:koin-bom:$koin_version")) implementation("io.insert-koin:koin-core") } commonTest.dependencies { implementation("io.insert-koin:koin-test") } androidMain.dependencies { implementation("io.insert-koin:koin-android") } } } ``` -------------------------------- ### Configure Retrofit with Koin Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/binding-patterns.md Provides examples for setting up Retrofit network modules using both Koin DSL and Annotations. ```kotlin interface ApiService { @GET("users/{id}") suspend fun getUser(@Path("id") id: String): User } // Builder functions - Koin resolves parameters automatically fun createOkHttpClient(): OkHttpClient = OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) .build() fun createRetrofit(client: OkHttpClient): Retrofit = Retrofit.Builder() .baseUrl("https://api.example.com/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() fun createApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java) val networkModule = module { single { create(::createOkHttpClient) } single { create(::createRetrofit) } single { create(::createApiService) } } ``` ```kotlin @Module class NetworkModule { @Single fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .build() @Single fun provideRetrofit(client: OkHttpClient): Retrofit = Retrofit.Builder() .baseUrl("https://api.example.com/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() @Single fun provideApiService(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java) } ``` -------------------------------- ### Start Koin in Kotlin Application Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/koin.md Initialize Koin by calling `startKoin` with your module definitions. This is the entry point for Koin in your application. ```kotlin fun main() { startKoin { modules(...) } } ``` -------------------------------- ### Setup Fragment Factory in Activity Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/fragment-factory.md Initialize the fragment factory by calling setupKoinFragmentFactory before super.onCreate. ```kotlin class MyActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { // Must be called BEFORE super.onCreate() setupKoinFragmentFactory() super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } } ``` -------------------------------- ### Define Koin application with annotations Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/starting-koin.md Setup for using the Koin Compiler Plugin with module scanning. ```kotlin @Module @Configuration @ComponentScan("com.myapp") class MyModule @KoinApplication class MyApp ``` -------------------------------- ### Setup Koin for Compose Multiplatform Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/gradle.md Configure dependencies for Compose Multiplatform projects. ```kotlin dependencies { implementation(platform("io.insert-koin:koin-bom:$koin_version")) implementation("io.insert-koin:koin-compose") implementation("io.insert-koin:koin-compose-viewmodel") implementation("io.insert-koin:koin-compose-viewmodel-navigation") } ``` -------------------------------- ### Koin Database Module Setup (SqlDelight) Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-mp/kmp.md Sets up Koin modules for SqlDelight database integration. Includes platform-specific driver factories. ```kotlin // commonMain expect class DriverFactory { fun createDriver(): SqlDriver } val databaseModule = module { single { DriverFactory().createDriver() } single { AppDatabase(get()) } single { get().userQueries } } // androidMain actual class DriverFactory(private val context: Context) { actual fun createDriver(): SqlDriver { return AndroidSqliteDriver(AppDatabase.Schema, context, "app.db") } } // iosMain actual class DriverFactory { actual fun createDriver(): SqlDriver { return NativeSqliteDriver(AppDatabase.Schema, "app.db") } } ``` -------------------------------- ### Koin Application Setup with Annotations Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/multi-module.md Configure the Koin application using annotations, defining the root module that includes all feature modules. ```kotlin @KoinApplication(AppModule::class) class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@MyApplication) } } } // Root module includes all features @Module(includes = [LoginModule::class, HomeModule::class, ProfileModule::class]) class AppModule ``` -------------------------------- ### Start Koin in Application Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/android-viewmodel.md Initializes Koin with Android context, logger, and defined modules in the Application class. ```kotlin class MainApplication : Application(){ override fun onCreate() { super.onCreate() startKoin{ androidLogger() androidContext(this@MainApplication) modules(appModule) } } } ``` -------------------------------- ### Start Compose UI on iOS Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/cmp.md Expose the Compose UI to the iOS platform via a ViewController. ```kotlin fun MainViewController() = ComposeUIViewController { App() } ``` -------------------------------- ### Basic KoinTest Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-ktor/ktor-testing.md Uses KoinTestRule to manage Koin lifecycle within a standard JUnit test class. ```kotlin class UserServiceTest : KoinTest { @get:Rule val koinTestRule = KoinTestRule.create { modules(testModule) } private val userService: UserService by inject() @Test fun `should return user`() { val user = userService.getUser("123") assertNotNull(user) } } val testModule = module { single { MockUserRepository() } singleOf(::UserService) } ``` -------------------------------- ### Koin Version Catalog - Before KSP Source: https://github.com/insertkoinio/koin/blob/main/docs/migration/from-ksp-to-compiler-plugin.md Example of a TOML version catalog configuration for Koin using KSP. ```toml [versions] koin = "4.0.0" koin-ksp = "2.0.0" # Separate versioning for KSP annotations ksp = "2.0.0-1.0.22" [libraries] koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" } koin-annotations = { module = "io.insert-koin:koin-annotations", version.ref = "koin-ksp" } koin-ksp-compiler = { module = "io.insert-koin:koin-ksp-compiler", version.ref = "koin-ksp" } [plugins] ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } ``` -------------------------------- ### Application Setup with Koin Annotations Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/hilt-migration.md Set up your Koin application using annotations. Modules tagged with `@Configuration` are automatically discovered. You can also explicitly list modules. ```kotlin @KoinApplication class MyApplication : Application() { override fun onCreate() { super.onCreate( startKoin { androidLogger() androidContext(this@MyApplication) } } } ``` -------------------------------- ### Kotlin Koin Core Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/koin.md Add the Koin BOM and `koin-core` dependency for Kotlin projects. This is the recommended way to manage Koin versions. ```kotlin dependencies { implementation(platform("io.insert-koin:koin-bom:$koin_version")) implementation("io.insert-koin:koin-core") } ``` -------------------------------- ### Basic Koin Startup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/start-koin.md Use this for standard applications to register Koin modules in the GlobalContext. ```kotlin startKoin { modules(appModule) } ``` -------------------------------- ### Organizing Dependencies with Modules Source: https://github.com/insertkoinio/koin/blob/main/docs/intro/what-is-dependency-injection.md Shows how to group related dependencies into separate modules for better code organization and how to start Koin with these modules. ```kotlin val dataModule = module { single() single() } val domainModule = module { single() single() } val presentationModule = module { viewModel() } startKoin { modules(dataModule, domainModule, presentationModule) } ``` -------------------------------- ### Gradle Setup for KSP Processor Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/annotations-ksp.md Configure your build.gradle.kts file to include the KSP plugin and necessary Koin dependencies for annotations processing. ```kotlin plugins { id("com.google.devtools.ksp") version "$ksp_version" } dependencies { implementation(platform("io.insert-koin:koin-bom:$koin_version")) implementation("io.insert-koin:koin-core") implementation("io.insert-koin:koin-annotations:$koin_ksp_version") ksp("io.insert-koin:koin-ksp-compiler:$koin_ksp_version") } ``` -------------------------------- ### Initialize Koin in Application Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/android-compose.md Starts Koin in the Application class using startKoin, providing the Android context and module definitions. ```kotlin class MainApplication : Application(){ override fun onCreate() { super.onCreate() startKoin{ androidLogger() androidContext(this@MainApplication) modules(appModule) } } } ``` -------------------------------- ### Koin Version Catalog - After Compiler Plugin Source: https://github.com/insertkoinio/koin/blob/main/docs/migration/from-ksp-to-compiler-plugin.md Example of a TOML version catalog configuration for Koin using the Compiler Plugin. ```toml [versions] koin = "4.2.0" koin-plugin = "1.0.0" [libraries] koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" } koin-annotations = { module = "io.insert-koin:koin-annotations", version.ref = "koin" } [plugins] koin-compiler = { id = "io.insert-koin.compiler.plugin", version.ref = "koin-plugin" } ``` -------------------------------- ### Koin NoBeanDefFoundException Example Source: https://github.com/insertkoinio/koin/blob/main/docs/intro/koin-vs-hilt.md Illustrates a typical Koin error message when a requested bean definition is not found, guiding the user to check module definitions. ```java org.koin.core.error.NoBeanDefFoundException: No definition found for class 'com.app.UserRepository'. Check your module definitions. ``` -------------------------------- ### Koin Annotations - Unchanged Examples Source: https://github.com/insertkoinio/koin/blob/main/docs/migration/from-ksp-to-compiler-plugin.md Demonstrates that Koin annotations like @Singleton, @Factory, @KoinViewModel, and @Module/@ComponentScan remain the same after migration. ```kotlin // No changes needed! @Singleton class UserRepository(private val database: Database) @Factory class GetUserUseCase(private val repository: UserRepository) @KoinViewModel class UserViewModel(private val useCase: GetUserUseCase) : ViewModel() @Module @ComponentScan("com.myapp") class AppModule ``` -------------------------------- ### Koin Startup Methods Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/start-koin.md Overview of the primary functions used to initialize Koin in different application contexts. ```APIDOC ## Koin Startup Methods ### Description Methods to initialize Koin instances for various use cases. ### Methods - **startKoin { }**: Registers in GlobalContext for standard apps. - **koinApplication { }**: Creates an isolated instance for testing or SDKs. - **koinConfiguration { }**: Configuration for Compose or Ktor. - **startKoin()**: Typed startup using the Koin Compiler Plugin. ### Request Example ```kotlin startKoin { modules(appModule) } ``` ``` -------------------------------- ### Koin Compiler Plugin Setup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-annotations/start.md Add the Koin Compiler Plugin and necessary Koin libraries to your project's build script. ```kotlin plugins { alias(libs.plugins.koin.compiler) } dependencies { implementation(libs.koin.core) implementation(libs.koin.annotations) } ``` -------------------------------- ### Install and Monitor Isolated Koin in Ktor Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-ktor/ktor-isolated.md Installs the KoinIsolated plugin and subscribes to Koin lifecycle events within a Ktor application. Ensure KoinIsolated is installed before subscribing to its events. ```kotlin fun Application.main() { install(KoinIsolated) { slf4jLogger() modules(appModule) } // Monitor Koin lifecycle environment.monitor.subscribe(KoinApplicationStarted) { log.info("Isolated Koin started") } environment.monitor.subscribe(KoinApplicationStopped) { log.info("Isolated Koin stopped") } } ``` -------------------------------- ### Install KoinIsolated Plugin Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-ktor/ktor-isolated.md Basic configuration for installing the KoinIsolated plugin in a Ktor application. ```kotlin fun Application.main() { install(KoinIsolated) { slf4jLogger() modules(appModule) } } ``` -------------------------------- ### Console Application with Koin Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/koin-component.md Example of setting up and running a console application using Koin. It demonstrates injecting dependencies into a `ConsoleApp` class and starting/stopping the Koin container. ```kotlin class ConsoleApp : KoinComponent { private val logger: Logger by inject() private val dataProcessor: DataProcessor by inject() fun run() { logger.info("Starting application") dataProcessor.process() logger.info("Application finished") } } fun main() { startKoin { modules(appModule) } ConsoleApp().run() stopKoin() } ``` -------------------------------- ### Compare Koin Configuration Approaches Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/kotlin-annotations.md Demonstrates the syntax differences between using Koin annotations and the Compiler Plugin DSL. ```kotlin @Module @ComponentScan("org.koin.sample") @Configuration class AppModule @Singleton class UserApplication(private val userService: UserService) @Singleton class UserRepositoryImpl : UserRepository @Singleton class UserServiceImpl(private val userRepository: UserRepository) : UserService ``` ```kotlin val appModule = module { single() single() bind UserRepository::class single() bind UserService::class } ``` -------------------------------- ### Method Injection Example Source: https://github.com/insertkoinio/koin/blob/main/docs/intro/what-is-dependency-injection.md A simple example of a class that accepts a dependency through a method, useful for optional or dynamic dependencies. ```kotlin class ReportGenerator { fun generateReport(data: DataSource) { // Use data to generate report } } ``` -------------------------------- ### Eager Instance Retrieval with get() Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/koin-component.md Use `get()` to retrieve an instance immediately when the component is constructed. The instance is available in the `init` block. ```kotlin class MyComponent : KoinComponent { // Instance retrieved immediately during construction val service: MyService = get() init { service.doSomething() // Already available } } ``` -------------------------------- ### Koin BOM Setup with Version Catalogs Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/koin.md Configure Koin dependencies using a version catalog for consistent management. Ensure the BOM version is defined in `[versions]` and library modules are referenced. ```toml [versions] koin-bom = "4.1.1" # Stable version [libraries] koin-bom = { module = "io.insert-koin:koin-bom", version.ref = "koin-bom" } koin-core = { module = "io.insert-koin:koin-core" } koin-android = { module = "io.insert-koin:koin-android" } koin-androidx-compose = { module = "io.insert-koin:koin-androidx-compose" } koin-compose = { module = "io.insert-koin:koin-compose" } koin-compose-viewmodel = { module = "io.insert-koin:koin-compose-viewmodel" } koin-ktor = { module = "io.insert-koin:koin-ktor" } koin-test = { module = "io.insert-koin:koin-test" } ``` -------------------------------- ### Avoid get() in Constructors Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/injection.md Avoid calling get() directly within constructors to prevent side effects and allow Koin to handle dependency injection naturally. ```kotlin // Bad - side effects in constructor class MyService( private val repo: UserRepository = get() // Don't do this! ) // Good - let Koin inject class MyService(private val repo: UserRepository) ``` -------------------------------- ### Injection with Parameters using `inject` and `get` Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/injection.md Provide parameters to factory instances using `parametersOf()` with `by inject` or `get()`. The parameters must match the order and types defined in the factory. ```kotlin // by inject() private val presenter: UserPresenter by inject { parametersOf("user123") } // get() val presenter: UserPresenter = get { parametersOf("user123") } ``` -------------------------------- ### Descriptive Test Naming Examples Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/instrumented-testing.md Provides examples of good and bad test naming conventions. Emphasizes using descriptive names that clearly indicate the test's purpose and expected outcome. ```kotlin // ✅ Good @Test fun loginWithValidCredentials_navigatesToHomeScreen() @Test fun loginWithInvalidEmail_showsEmailError() // ❌ Bad @Test fun test1() @Test fun testLogin() ``` -------------------------------- ### Eager Module Creation Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/modules.md Configure a module to create its singletons immediately at startup by setting `createdAtStart = true`. ```kotlin val coreModule = module(createdAtStart = true) { single() single() } ``` -------------------------------- ### Fragment Factory Quick Reference Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/fragment-factory.md Summary of essential Koin Fragment Factory commands. ```text fragment { MyFragment(get()) } ``` ```text setupKoinFragmentFactory() ``` ```text setupKoinFragmentFactory(scope) ``` ```text .replace(R.id.container) ``` -------------------------------- ### Initialize Koin with Extension Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/extension-manager.md Register the extension during the Koin startup process. ```kotlin startKoin { myExtension() // Register extension modules(appModule) } ``` -------------------------------- ### Start Koin with @KoinApplication Source: https://github.com/insertkoinio/koin/blob/main/docs/quickstart/android-annotations.md Automatically discover and load modules annotated with `@Configuration` or `@Module`. Requires `org.koin.ksp.generated.*` import. Configure Android-specific settings like `androidContext`. ```kotlin import org.koin.android.ext.koin.androidContext import org.koin.core.annotation.KoinApplication import org.koin.ksp.generated.* @KoinApplication class MainApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@MainApplication) } } } ``` -------------------------------- ### Initialize Koin with AndroidX Startup Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/start.md Using the KoinStartup interface to integrate with AndroidX App Startup for early initialization. ```kotlin class MainApplication : Application(), KoinStartup { override fun onKoinStartup() = koinConfiguration { androidContext(this@MainApplication) modules(appModule) } override fun onCreate() { super.onCreate() } } ``` ```kotlin class CrashTrackerInitializer : Initializer, KoinComponent { private val crashTrackerService: CrashTrackerService by inject() override fun create(context: Context) { crashTrackerService.configure(context) } override fun dependencies(): List>> { return listOf(KoinInitializer::class.java) } } ``` -------------------------------- ### Initialize Koin in Application Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/entry-points.md Configure Koin within the Application class using startKoin to set up the logger, context, and modules. ```kotlin class MyApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@MyApplication) modules(appModule, networkModule, dataModule) } } } ``` -------------------------------- ### Define a Koin Module Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-test/verify.md Example of defining a Koin module with included modules and a ViewModel. ```kotlin val niaAppModule = module { includes( jankStatsKoinModule, dataKoinModule, syncWorkerKoinModule, topicKoinModule, authorKoinModule, interestsKoinModule, settingsKoinModule, bookMarksKoinModule, forYouKoinModule ) viewModel() } ``` -------------------------------- ### Eager Injection in Services Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/entry-points.md Uses get() for immediate dependency resolution within a Service. ```kotlin class DownloadService : Service() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { // Eager injection - created immediately val downloader: FileDownloader = get() val url = intent?.getStringExtra("URL") ?: "" downloader.start(url) return START_STICKY } } ``` -------------------------------- ### Koin Integration for Ktor Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/start-koin.md Install Koin as a plugin in a Ktor application. Uses `slf4jLogger()` for logging. ```kotlin fun Application.module() { install(Koin) { slf4jLogger() modules(appModule) } } ``` -------------------------------- ### Koin Configuration Options Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/start-koin.md Detailed configuration settings available during Koin startup. ```APIDOC ## Koin Configuration ### Description Configure logging, module loading, and property sources during startup. ### Configuration Options - **logger()**: Set logging level and implementation. - **modules()**: Load modules immediately. - **lazyModules()**: Load modules in background. - **properties()**: Load properties from map. - **fileProperties()**: Load from koin.properties file. - **environmentProperties()**: Load from system/environment. - **createEagerInstances()**: Create all createdAtStart singletons. - **allowOverride()**: Enable/disable definition overriding. ### Request Example ```kotlin startKoin { logger(Level.INFO) environmentProperties() modules(coreModule, networkModule) allowOverride(false) } ``` -------------------------------- ### Circular Dependency Example Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/troubleshooting.md Demonstrates a circular dependency between ServiceA and ServiceB, which causes a runtime error. ```kotlin // Circular dependency class ServiceA(val serviceB: ServiceB) class ServiceB(val serviceA: ServiceA) module { single { ServiceA(get()) } single { ServiceB(get()) } // ERROR: Circular dependency! } ``` -------------------------------- ### Initialize Koin with Shared Module Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/kmp-shared-modules.md Sets up the Koin application with common and platform-specific modules. Use this as a base for platform extensions. ```kotlin // commonMain/kotlin/di/KoinHelper.kt fun initKoin(config: KoinAppDeclaration? = null): KoinApplication { return startKoin { includes(config) // Platform-specific extensions modules( sharedModule, dataModule, domainModule, platformModule ) } } ``` -------------------------------- ### Eager Instance Creation with createdAtStart Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-core/definitions.md Ensure instances are created eagerly at startup using createdAtStart() in the compiler plugin DSL or by setting createdAtStart = true in the classic DSL. ```kotlin // Compiler Plugin DSL single() withOptions { createdAtStart() } // Classic DSL single(createdAtStart = true) { ConfigManager() } ``` -------------------------------- ### Koin BOM Setup Without Version Catalogs Source: https://github.com/insertkoinio/koin/blob/main/docs/setup/koin.md Integrate Koin using the BOM without version catalogs. Declare the BOM version and then add Koin dependencies without specifying their versions. ```kotlin dependencies { // Declare koin-bom version implementation(platform("io.insert-koin:koin-bom:$koin_version")) // Declare the koin dependencies without versions implementation("io.insert-koin:koin-android") implementation("io.insert-koin:koin-core-coroutines") implementation("io.insert-koin:koin-androidx-workmanager") // If you need to specify a different version for a specific dependency implementation("io.insert-koin:koin-androidx-navigation:1.2.3-alpha03") // Works with test libraries too! testImplementation("io.insert-koin:koin-test-junit4") testImplementation("io.insert-koin:koin-android-test") } ``` -------------------------------- ### BroadcastReceiver Injection Best Practices Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-android/entry-points.md Uses get() for efficient dependency access in short-lived receivers. ```kotlin class AlarmReceiver : BroadcastReceiver(), KoinComponent { override fun onReceive(context: Context?, intent: Intent?) { // Use get() for immediate access (more efficient for receivers) val repository: AlarmRepository = get() // Offload work to a Service or WorkManager val workRequest = OneTimeWorkRequestBuilder() .setInputData(workDataOf("alarm_id" to intent?.getIntExtra("ID", -1))) .build() WorkManager.getInstance(context!!).enqueue(workRequest) } } ``` -------------------------------- ### Testing navigation in Compose with Koin Source: https://github.com/insertkoinio/koin/blob/main/docs/reference/koin-compose/compose-testing.md Verifies navigation state by capturing the NavHostController during the Compose test setup. ```kotlin class NavigationTest : KoinTest { @get:Rule val koinTestRule = KoinTestRule.create { modules(testModule) } @get:Rule val composeTestRule = createComposeRule() @Test fun navigatesToDetail() { lateinit var navController: NavHostController composeTestRule.setContent { navController = rememberNavController() AppNavigation(navController) } // Navigate to detail composeTestRule.onNodeWithText("View Details").performClick() // Verify navigation assertEquals("detail/123", navController.currentDestination?.route) } @Test fun backNavigationWorks() { lateinit var navController: NavHostController composeTestRule.setContent { navController = rememberNavController() AppNavigation(navController) } // Navigate forward composeTestRule.onNodeWithText("View Details").performClick() // Navigate back composeTestRule.onNodeWithContentDescription("Back").performClick() // Verify back at home assertEquals("home", navController.currentDestination?.route) } } ```