### KSP Plugin Configuration for Koin Annotations Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md This snippet shows how to apply the KSP plugin in the composeApp's build.gradle.kts file. This is a prerequisite for using Koin Annotations. ```kotlin alias(libs.plugins.ksp) ``` -------------------------------- ### PlatformComponent and NativeModule Implementations (iOS) Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md Provides the iOS-specific 'actual' implementations for `PlatformComponent` and `NativeModule`. `PlatformComponent` returns a hardcoded iOS string, and `NativeModule` uses `@ComponentScan` for native component discovery. ```kotlin @Module @ComponentScan("com.jetbrains.kmpapp.native") actual class NativeModule ``` ```kotlin @Single actual class PlatformComponent{ actual fun sayHello() : String = "I'm iOS" } ``` -------------------------------- ### Customizing Koin Configuration with initKoin Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md Shows a flexible way to initialize Koin in multiplatform projects using an `initKoin` function that accepts an optional configuration lambda. This allows for platform-specific configurations, such as injecting the Android context. ```kotlin // config allow to extend Koin configuration from caller side fun initKoin(config : KoinAppDeclaration ?= null) { startKoin { modules( AppModule().module, ) // call for any extra configuration config?.invoke(this) } } ``` ```kotlin class MuseumApp : Application() { override fun onCreate() { super.onCreate() initKoin { androidContext(this@MuseumApp) } } } ``` -------------------------------- ### Start Koin Application with Explicit Modules Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md Initiate a Koin application using the `@KoinApplication` annotation and explicitly list the modules to be used. This approach requires importing generated extension functions for module and application startup. ```kotlin // The import below gives you access to generated extension functions // like MyModule.module and MyApp.startKoin() import org.koin.ksp.generated.* @KoinApplication(modules = [MyModule::class]) object MyApp fun main() { MyApp.startKoin { printLogger() } // Just use your Koin API as regular KoinPlatform.getKoin().get() } ``` -------------------------------- ### Koin Annotations Dependency Declaration Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md This snippet demonstrates how to add the Koin Annotations dependency to your composeApp's build.gradle.kts file. This makes the Koin Annotations library available for use. ```kotlin api(libs.koin.annotations) ``` -------------------------------- ### PlatformComponent and NativeModule Implementations (Android) Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md Provides the Android-specific 'actual' implementations for `PlatformComponent` and `NativeModule`. `PlatformComponent` takes an Android `Context` and returns a platform-specific string, while `NativeModule` uses `@ComponentScan` to discover native components. ```kotlin @Module @ComponentScan("com.jetbrains.kmpapp.native") actual class NativeModule ``` ```kotlin @Single actual class PlatformComponent(val context: Context){ actual fun sayHello() : String = "I'm Android - $context" } ``` -------------------------------- ### Setup KSP Plugin for Koin Annotations Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/setup/annotations.md This snippet demonstrates how to apply the Google KSP Gradle plugin, which is a prerequisite for using Koin Annotations. Ensure the KSP version is compatible with your Kotlin version. No specific input or output is defined, but it's essential for enabling annotation processing. ```kotlin plugins { id("com.google.devtools.ksp") version "$ksp_version" } ``` -------------------------------- ### Automatic Module Loading with @Configuration Annotation Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md Create modules that are automatically loaded by Koin using the `@Configuration` annotation in conjunction with `@Module`. This simplifies the startup process by eliminating the need for explicit module declaration in `@KoinApplication`. ```kotlin // Module with configuration - automatically included in default config @Module @Configuration class MyModule ``` ```kotlin // The import below gives you access to generated extension functions // This approach loads all modules marked with @Configuration automatically import org.koin.ksp.generated.* @KoinApplication object MyApp fun main() { MyApp.startKoin { printLogger() } // Just use your Koin API as regular KoinPlatform.getKoin().get() } ``` -------------------------------- ### KSP Common Task Trigger Configuration Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md This configuration ensures that KSP tasks, except for 'kspCommonMainKotlinMetadata', depend on 'kspCommonMainKotlinMetadata'. This establishes the correct build order for Koin Annotations processing. ```kotlin project.tasks.withType(KotlinCompilationTask::class.java).configureEach { if(name != "kspCommonMainKotlinMetadata") { dependsOn("kspCommonMainKotlinMetadata") } } ``` -------------------------------- ### Define a Koin Module with @Module Annotation Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md Declare a Koin module by annotating a class with `@Module`. This class will serve as a container for Koin definitions, allowing for organized dependency injection setup. ```kotlin // Declare a module and scan for annotations @Module class MyModule ``` -------------------------------- ### KSP Compiler Task Configuration Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md This snippet configures the KSP compiler tasks for various platforms (common, Android, iOS). It ensures the Koin Annotations compiler is added to the necessary tasks. ```kotlin dependencies { add("kspCommonMainMetadata", libs.koin.ksp.compiler) add("kspAndroid", libs.koin.ksp.compiler) add("kspIosX64", libs.koin.ksp.compiler) add("kspIosArm64", libs.koin.ksp.compiler) add("kspIosSimulatorArm64", libs.koin.ksp.compiler) } ``` -------------------------------- ### Koin @Configuration Annotation Example (Kotlin) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/annotations-inventory.md Demonstrates how to use the @Configuration annotation in Kotlin to associate modules with specific configurations (tags/flavors) for conditional loading. It shows examples for default, multiple, and combined configurations. ```kotlin @Module @Configuration class MyModule ``` ```kotlin @Module @Configuration("prod", "test") class MyModule ``` ```kotlin @Module @Configuration("default", "test") class MyModule ``` -------------------------------- ### KSP Common Source Set Configuration Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md This configuration snippet in build.gradle.kts ensures that KSP generated metadata is included in the common main source set, enabling Koin Annotations to process it correctly. ```kotlin sourceSets.named("commonMain").configure { kotlin.srcDir("build/generated/ksp/metadata/commonMain/kotlin") } ``` -------------------------------- ### Android & Ktor App KSP Setup for Koin Annotations Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/setup/annotations.md This configuration integrates Koin Annotations into an Android or Ktor application using the KSP plugin. It includes applying the KSP plugin, adding Koin Annotations and its KSP compiler as dependencies, and setting the appropriate source set. This setup enables Koin's annotation-driven dependency injection for your app. ```kotlin plugins { id("com.google.devtools.ksp") version "$ksp_version" } dependencies { // Koin implementation("io.insert-koin:koin-android:$koin_version") // Koin Annotations implementation("io.insert-koin:koin-annotations:$koin_annotations_version") // Koin Annotations KSP Compiler ksp("io.insert-koin:koin-ksp-compiler:$koin_annotations_version") } ``` -------------------------------- ### Koin @KoinApplication Annotation Example (Kotlin) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/annotations-inventory.md Illustrates the use of the @KoinApplication annotation in Kotlin to designate a class as a Koin application entry point. It shows how to generate bootstrap functions like startKoin() and koinApplication() for default, specific configurations, and with included modules. ```kotlin @KoinApplication class MyApp ``` ```kotlin @KoinApplication(configurations = ["default", "prod"]) class MyApp ``` ```kotlin @KoinApplication( configurations = ["default"], modules = [CoreModule::class, ApiModule::class] ) class MyApp ``` ```kotlin MyApp.startKoin { printLogger() // additional configuration } ``` -------------------------------- ### Injecting Dynamic Parameters with @InjectedParam Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md Demonstrates how to use the `@InjectedParam` annotation in Koin for injecting dynamic parameters into a factory. The `IdGenerator` class uses a prefix that is provided at runtime via `parametersOf`. ```kotlin @Factory class IdGenerator(@InjectedParam private val prefix : String) { fun generate() : String = prefix + KoinPlatformTools.generateId() } ``` ```kotlin val idGen = KoinPlatform.getKoin().get { parametersOf("_prefix_") }.generate() println("Id => $idGen") ``` -------------------------------- ### PlatformComponent and NativeModule Definitions (Common) Source: https://github.com/insertkoinio/koin-annotations/blob/main/example-cmp/README.md Defines the `PlatformComponent` as an 'expect' class and `NativeModule` as an 'expect' class using Koin annotations for multiplatform sharing. This is the common definition used across different platforms. ```kotlin @Module expect class NativeModule ``` ```kotlin expect class PlatformComponent { fun sayHello() : String } ``` -------------------------------- ### Generated @Monitor Proxy Class Example Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/monitor.md An example of the proxy class generated by the compiler for a class annotated with @Monitor. It wraps method calls with Kotzilla tracing. ```kotlin /** * Generated by @Monitor - Koin proxy for 'UserService' */ class UserServiceProxy(userRepository: UserRepository) : UserService(userRepository) { override fun findUser(id: String): User? { return KotzillaCore.getDefaultInstance().trace("UserService.findUser") { super.findUser(id) } } override suspend fun createUser(userData: UserData): User { return KotzillaCore.getDefaultInstance().suspendTrace("UserService.createUser") { super.createUser(userData) } } } ``` -------------------------------- ### Kotlin Multiplatform Setup for Koin Annotations Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/setup/annotations.md This snippet configures Koin Annotations for a Kotlin Multiplatform project. It involves applying the KSP plugin, adding Koin core and Koin Annotations dependencies to the commonMain source set, configuring the KSP source set for commonMain metadata, and setting up KSP dependencies for various targets. This ensures annotation processing works across all your Kotlin targets. ```kotlin plugins { id("com.google.devtools.ksp") } kotlin { sourceSets { // Add Koin Annotations commonMain.dependencies { // Koin implementation("io.insert-koin:koin-core:$koin_version") // Koin Annotations api("io.insert-koin:koin-annotations:$koin_annotations_version") } } // KSP Common sourceSet sourceSets.named("commonMain").configure { kotlin.srcDir("build/generated/ksp/metadata/commonMain/kotlin") } } // KSP Tasks dependencies { add("kspCommonMainMetadata", libs.koin.ksp.compiler) add("kspAndroid", libs.koin.ksp.compiler) add("kspIosX64", libs.koin.ksp.compiler) add("kspIosArm64", libs.koin.ksp.compiler) add("kspIosSimulatorArm64", libs.koin.ksp.compiler) } // Trigger Common Metadata Generation from Native tasks tasks.matching { it.name.startsWith("ksp") && it.name != "kspCommonMainKotlinMetadata" }.configureEach { dependsOn("kspCommonMainKotlinMetadata") } ``` -------------------------------- ### Deprecated: Enable Default Module in Gradle Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md This section details a deprecated approach for enabling a default module where Koin compiler would place uncategorized definitions. It is recommended to use explicit module organization with `@Configuration` and `@KoinApplication` instead. ```groovy // in build.gradle or build.gradle.kts ksp { arg("KOIN_DEFAULT_MODULE","true") } ``` -------------------------------- ### Bootstrap Koin Application with @KoinApplication Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/modules.md The @KoinApplication annotation is used on an entry point class to generate functions for starting a Koin application. It can load default configurations, specific configurations, and include modules directly. It generates methods like startKoin() and koinApplication() which can be customized with additional Koin configurations. ```kotlin import org.koin.ksp.generated.* // load default configuration @KoinApplication object MyApp @KoinApplication( configurations = ["default", "production"], modules = [MyModule::class] ) object MyAppWithSpecificConfig fun main() { // Option 1: Start Koin directly MyApp.startKoin() // Option 2: Get KoinApplication instance val koinApp = MyApp.koinApplication() // Start Koin with custom configuration MyApp.startKoin { printLogger() // Add other Koin configuration } // Or with koinApplication MyApp.koinApplication { printLogger() } } ``` -------------------------------- ### Initialize Kotzilla Analytics in Koin Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/monitor.md Initializes Koin and enables Kotzilla analytics using the analytics() function. This integrates performance monitoring into your Koin setup. ```kotlin import io.kotzilla.sdk.analytics.koin.analytics fun initKoin() { startKoin { // Enable Kotzilla monitoring analytics() modules(appModule) } } ``` -------------------------------- ### Enable Compile-Time Koin Configuration Check in Gradle Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md Activate compile-time verification of your Koin configuration by adding the `"KOIN_CONFIG_CHECK","true"` argument to your KSP options in the Gradle build file. This ensures all dependencies and modules are correctly declared and accessible. ```groovy // in build.gradle or build.gradle.kts ksp { arg("KOIN_CONFIG_CHECK","true") } ``` -------------------------------- ### Using Default Module (Deprecated) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/modules.md Demonstrates how to use the deprecated default module to host definitions when explicit modules are not specified. It shows the import required for generated extension functions and two ways to include the default module in Koin setup. ```kotlin import org.koin.ksp.generated.* fun main() { startKoin { defaultModule() } } // or fun main() { startKoin { modules( defaultModule ) } } ``` -------------------------------- ### Kotzilla Platform Configuration JSON Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/monitor.md Example JSON configuration for the Kotzilla SDK, including SDK version, application ID, package name, key ID, and API key. This is used for sending monitoring data to the Kotzilla Platform. ```json { "sdkVersion": "latest.version", "keys": [ { "appId": "your-app-id", "applicationPackageName": "com.example.app", "keyId": "your-key-id", "apiKey": "your-api-key" } ] } ``` -------------------------------- ### Pro-Guard Rules for Koin Annotations SDK Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md These Pro-Guard rules are essential for embedding Koin Annotations as an SDK. They ensure that annotation definitions and classes annotated with Koin annotations are kept during the Pro-Guard obfuscation process. ```proguard # Keep annotation definitions -keep class org.koin.core.annotation.** { *; } # Keep classes annotated with Koin annotations -keep @org.koin.core.annotation.* class * { *; } ``` -------------------------------- ### Property Injection with @Property in Kotlin Source: https://context7.com/insertkoinio/koin-annotations/llms.txt Shows how to resolve Koin properties directly in constructor parameters using the @Property annotation. It includes defining default property values with @PropertyValue and provides an example of how to start Koin with custom properties. Dependencies include Koin core annotations and HTTP client libraries. ```kotlin import org.koin.core.annotation.Factory import org.koin.core.annotation.Property import org.koin.core.annotation.PropertyValue @Factory class ApiClient( @Property("api.url") val baseUrl: String, @Property("api.timeout") val timeout: Int, @Property("api.key") val apiKey: String ) { companion object { @PropertyValue("api.timeout") const val DEFAULT_TIMEOUT = 30000 } fun makeRequest(endpoint: String): Response { return HttpClient.get("$baseUrl/$endpoint") { timeout(timeout.toLong()) header("X-API-Key", apiKey) } } } // Usage with properties import org.koin.ksp.generated.* fun main() { startKoin { modules(MyModule().module) properties( mapOf( "api.url" to "https://api.example.com", "api.timeout" to 60000, "api.key" to "secret-key-123" ) ) } val client = KoinPlatform.getKoin().get() val response = client.makeRequest("users/123") } ``` -------------------------------- ### Koin @Monitor Annotation for Performance Tracing (Kotlin) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/annotations-inventory.md Shows how to apply the @Monitor annotation in Kotlin to a class or function for automatic monitoring and performance tracing via the Kotzilla Platform. This example demonstrates monitoring a UserService class. ```kotlin @Monitor class UserService(private val userRepository: UserRepository) { fun findUser(id: String): User? = userRepository.findById(id) } ``` -------------------------------- ### Declare a Koin Component with @Single Annotation Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md Tag a Kotlin class with the `@Single` annotation to declare it as a Koin definition. This is a straightforward way to make your component available for dependency injection through Koin. ```kotlin // Tag your component to declare a definition @Single class MyComponent ``` -------------------------------- ### Mixing Koin and JSR-330 Annotations Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md This example illustrates the seamless integration of JSR-330 annotations (`@Singleton`, `@Named`, `@Inject`) with Koin's native annotations (`@Single`, `@Factory`) within the same project and even within the same class, showcasing flexibility during migration. ```kotlin // JSR-330 style @Singleton @Named("primary") class PrimaryDatabase : Database // Koin style @Single @Named("secondary") class SecondaryDatabase : Database // Mixed in same class @Factory class DatabaseManager @Inject constructor( @Named("primary") private val primary: Database, @Named("secondary") private val secondary: Database ) ``` -------------------------------- ### Organize Modules with @Configuration for Environments Source: https://context7.com/insertkoinio/koin-annotations/llms.txt The @Configuration annotation allows grouping Koin modules for different environments, flavors, or feature sets. It enables conditional loading of modules based on specified configuration names, facilitating environment-specific setups. ```kotlin import org.koin.core.annotation.Module import org.koin.core.annotation.Configuration import org.koin.core.annotation.Single @Module @Configuration class DefaultModule { @Single fun provideLogger(): Logger = ConsoleLogger() } @Module @Configuration("production") class ProductionModule { @Single fun provideDatabase(): Database = PostgreSQLDatabase("prod-url") @Single fun provideCache(): Cache = RedisCache("prod-redis") } @Module @Configuration("development") class DevelopmentModule { @Single fun provideDatabase(): Database = InMemoryDatabase() @Single fun provideCache(): Cache = InMemoryCache() } @Module @Configuration("production", "staging") class CloudModule { @Single fun provideCloudStorage(): Storage = S3Storage() } // Application bootstrap import org.koin.core.annotation.KoinApplication @KoinApplication(configurations = ["default", "production"]) object ProductionApp @KoinApplication(configurations = ["default", "development"]) object DevelopmentApp // Usage import org.koin.ksp.generated.* fun main() { ProductionApp.startKoin { printLogger() } } ``` -------------------------------- ### JSR-330 @Qualifier Meta-Annotation Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Example of creating custom qualifier annotations using JSR-330's `@Qualifier` meta-annotation. This allows for type-safe and semantic differentiation of dependencies, as demonstrated with `@Database` and `@Cache`. ```kotlin import jakarta.inject.Qualifier @Qualifier annotation class Database @Qualifier annotation class Cache @Singleton @Database class DatabaseConfig @Singleton @Cache class CacheConfig ``` -------------------------------- ### JSR-330 @Singleton Annotation in Koin Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Example of using the JSR-330 `@Singleton` annotation, which is equivalent to Koin's `@Single` annotation. This ensures that only a single instance of the annotated class is created and managed by Koin. ```kotlin import jakarta.inject.Singleton @Singleton class DatabaseService ``` -------------------------------- ### Configure Koin Annotations KSP Compiler Options (Gradle Kotlin DSL) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/options.md Example of how to configure Koin Annotations KSP compiler options using the Gradle Kotlin DSL. These arguments customize the behavior of the KSP processor during compilation. ```kotlin ksp { arg("KOIN_CONFIG_CHECK", "true") arg("KOIN_LOG_TIMES", "true") arg("KOIN_DEFAULT_MODULE", "false") arg("KOIN_GENERATION_PACKAGE", "com.mycompany.koin.generated") arg("KOIN_USE_COMPOSE_VIEWMODEL", "true") arg("KOIN_EXPORT_DEFINITIONS", "true") } ``` -------------------------------- ### Injecting Lists of Dependencies with Koin Annotations Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Koin automatically resolves and injects collections of dependencies. This example demonstrates how to inject a `List` into the `LoggerAggregator` class using Koin's `@Single` annotation and how the DSL generates the `getAll()` function for list resolution. ```kotlin @Single @Named("InMemoryLogger") class LoggerInMemoryDataSource : LoggerDataSource @Single @Named("DatabaseLogger") class LoggerLocalDataSource(private val logDao: LogDao) : LoggerDataSource @Single class LoggerAggregator(val datasource : List) ``` ```kotlin single { LoggerAggregator(getAll()) } ``` -------------------------------- ### JSR-330 @Scope Meta-Annotation for Custom Scopes Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Demonstrates the creation of custom scope annotations using JSR-330's `@Scope` meta-annotation. This example defines a `RequestScoped` annotation and shows how it can be integrated with Koin's scoping system. ```kotlin import jakarta.inject.Scope @Scope annotation class RequestScoped // Use with Koin's scope system @Scope(name = "request") @RequestScoped class RequestProcessor ``` -------------------------------- ### Defining Components within a Class Module Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/modules.md Demonstrates how to define a Koin definition directly within a class module by annotating a function with definition annotations like `@Single`. The example shows defining a `myComponent` that depends on `MyDependency`. ```kotlin // given // class MyComponent(val myDependency : MyDependency) @Module class MyModule { @Single fun myComponent(myDependency : MyDependency) = MyComponent(myDependency) } ``` -------------------------------- ### Declare Koin Module with Annotated Components Source: https://context7.com/insertkoinio/koin-annotations/llms.txt The @Module annotation declares a class as a Koin module. It can include definitions for dependencies and can scan for annotated components using @ComponentScan. Dependencies can be provided via singletons or factories. This example shows module declaration and usage in application startup. ```kotlin import org.koin.core.annotation.Module import org.koin.core.annotation.ComponentScan import org.koin.core.annotation.Single @Module @ComponentScan("com.example.data") class DataModule { @Single fun provideDatabase(config: DatabaseConfig): Database { return Database.connect(config.url, config.credentials) } @Single fun provideApiClient(): ApiClient { return ApiClient.Builder() .baseUrl("https://api.example.com") .timeout(30000) .build() } } @Module(includes = [DataModule::class, NetworkModule::class]) class AppModule // Usage - loading modules import org.koin.ksp.generated.* fun main() { startKoin { modules( AppModule().module // Automatically includes DataModule and NetworkModule ) } } ``` -------------------------------- ### Including Modules with @Module Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/modules.md Explains how to include other class modules within a parent module using the `includes` attribute of the `@Module` annotation. It shows an example of `ModuleA` being included in `ModuleB` and how to load the root module (`ModuleB`) to include all nested modules. ```kotlin @Module class ModuleA @Module(includes = [ModuleA::class]) class ModuleB ``` ```kotlin // Use Koin Generation import org.koin.ksp.generated.* fun main() { startKoin { modules( // will load ModuleB & ModuleA ModuleB().module ) } } ``` -------------------------------- ### Scope Archetypes: @ActivityScope, @FragmentScope, @ViewModelScope in Kotlin Source: https://context7.com/insertkoinio/koin-annotations/llms.txt Utilizes predefined Koin scope annotations for common Android and multiplatform scope patterns. This example shows how to apply @ActivityScope, @FragmentScope, and @ViewModelScope to classes and integrate them within Android Activity, Fragment, and ViewModel contexts. Dependencies include Koin Android annotations and Android Jetpack components. ```kotlin import org.koin.android.annotation.ActivityScope import org.koin.android.annotation.FragmentScope import org.koin.core.annotation.ViewModelScope import org.koin.android.annotation.KoinViewModel import androidx.lifecycle.ViewModel @ActivityScope class ActivityTracker(val analytics: AnalyticsService) { private val screenViews = mutableListOf() fun trackScreen(screenName: String) { screenViews.add(screenName) analytics.logEvent("screen_view", mapOf("screen" to screenName)) } } @FragmentScope class FragmentState(val fragmentId: String) { var data: String? = null } @ViewModelScope class ViewModelRepository(val apiService: ApiService) { suspend fun fetchData(): Result = apiService.getData() } @KoinViewModel class MyViewModel( val repository: ViewModelRepository, val tracker: ViewModelRepository ) : ViewModel() // Usage in Android Activity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Create activity scope val activityScope = activityScope() val tracker = activityScope.get() tracker.trackScreen("MainActivity") } } // Usage in Fragment class MyFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val fragmentScope = fragmentScope() val state = fragmentScope.get() } } ``` -------------------------------- ### Bootstrap Koin Application with @KoinApplication Source: https://context7.com/insertkoinio/koin-annotations/llms.txt The @KoinApplication annotation generates Koin application bootstrap functions, simplifying the startup process by automatically loading configured modules. It supports defining configurations and directly specifying modules for application initialization. ```kotlin import org.koin.core.annotation.KoinApplication import org.koin.core.annotation.Configuration import org.koin.core.annotation.Module @Module @Configuration class AppModule @Module @Configuration("production") class ProductionModule @KoinApplication(configurations = ["default", "production"]) object MyApp // Usage - two generated functions available import org.koin.ksp.generated.* import org.koin.core.context.KoinPlatform fun main() { // Option 1: Start Koin directly MyApp.startKoin() // Option 2: Start with custom configuration MyApp.startKoin { printLogger() properties(mapOf("api.url" to "https://api.example.com")) } // Option 3: Get KoinApplication instance val koinApp = MyApp.koinApplication { printLogger() } // Use Koin val service = KoinPlatform.getKoin().get() } // Explicitly specify modules without configuration @KoinApplication(modules = [DataModule::class, NetworkModule::class]) object SimpleApp fun startSimple() { SimpleApp.startKoin() } ``` -------------------------------- ### Gradle/KSP Configuration for Koin Annotations Source: https://context7.com/insertkoinio/koin-annotations/llms.txt Sets up Koin Annotations with Google KSP in a Gradle build file. It includes necessary plugins, dependencies for Koin core and annotations, and configures KSP options for compile-time safety and Android specific source directory generation. ```kotlin // build.gradle.kts plugins { kotlin("jvm") version "2.0.20" id("com.google.devtools.ksp") version "2.0.20-1.0.24" } dependencies { implementation("io.insert-koin:koin-core:3.5.0") implementation("io.insert-koin:koin-annotations:2.3.0") ksp("io.insert-koin:koin-ksp-compiler:2.3.0") } // Configure generated source directory kotlin.sourceSets.main { kotlin.srcDir("build/generated/ksp/main/kotlin") } // KSP options for compile-time safety ksp { arg("KOIN_CONFIG_CHECK", "true") // Enable compile-time verification arg("KOIN_USE_COMPOSE_VIEWMODEL", "true") // For KMP ViewModels } // Android configuration android { applicationVariants.all { kotlin.sourceSets { getByName(name) { kotlin.srcDir("build/generated/ksp/$name/kotlin") } } } } ``` -------------------------------- ### KoinWorker Annotation for WorkManager Integration Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/annotations-inventory.md Declares a class as a `worker` definition for Android WorkManager integration. This annotation simplifies the setup of Koin-managed workers. ```kotlin import org.koin.android.annotation.KoinWorker import androidx.work.Worker @KoinWorker class MyWorker() : Worker() ``` -------------------------------- ### Share Expect/Actual Definitions using @ComponentScan Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/kmp.md This pattern demonstrates sharing definitions across platforms by using `@ComponentScan` in a common module and then providing platform-specific actual implementations for the expected classes. Constructors must match across platforms. ```kotlin // commonMain @Module @ComponentScan("com.jetbrains.kmpapp.native") class NativeModuleA() // package com.jetbrains.kmpapp.native @Factory expect class PlatformComponentA() { fun sayHello() : String } ``` ```kotlin // androidMain // package com.jetbrains.kmpapp.native actual class PlatformComponentA { actual fun sayHello() : String = "I'm Android - A" } // iOSMain // package com.jetbrains.kmpapp.native actual class PlatformComponentA { actual fun sayHello() : String = "I'm iOS - A" } ``` -------------------------------- ### Implement Platform Wrapper for Context Injection (Kotlin) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/kmp.md Demonstrates creating an expected 'ContextWrapper' class and 'ContextModule' in commonMain, with platform-specific implementations in androidMain and iOSMain. This allows injecting Android's Context on Android while providing a no-op or different implementation on iOS, minimizing dynamic wiring. ```kotlin // commonMain expect class ContextWrapper @Module expect class ContextModule() { @Single fun providesContextWrapper(scope : Scope) : ContextWrapper } ``` ```kotlin // androidMain actual class ContextWrapper(val context: Context) @Module actual class ContextModule { // needs androidContext() to be setup at start @Single actual fun providesContextWrapper(scope : Scope) : ContextWrapper = ContextWrapper(scope.get()) } ``` ```kotlin // iOSMain actual class ContextWrapper @Module actual class ContextModule { @Single actual fun providesContextWrapper(scope : Scope) : ContextWrapper = ContextWrapper() } ``` -------------------------------- ### Bypass Compile Safety Check with @Provided Annotation Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/start.md Exclude a parameter from compile-time configuration checks by annotating it with `@Provided`. This is useful when a type is provided externally to the current Koin Annotations configuration, indicating it's already declared in Koin. ```kotlin class MyProvidedComponent @Factory class MyPresenter(@Provided val provided : MyProvidedComponent) ``` -------------------------------- ### Annotations Overview Source: https://context7.com/insertkoinio/koin-annotations/llms.txt Koin Annotations uses annotations to define dependencies at compile time via KSP, generating Koin DSL code automatically. It supports Kotlin Multiplatform, Android, and JSR-330. ```APIDOC ## Koin Annotations Overview Koin Annotations is a pragmatic, lightweight dependency injection framework for Kotlin developers that brings annotation-based configuration to Koin projects, powered by Google KSP (Kotlin Symbol Processing). It provides a fast and intuitive way to declare dependency injection definitions through annotations, automatically generating the underlying Koin DSL code at compile time. This eliminates boilerplate while maintaining Koin's simplicity and performance characteristics. The framework supports Kotlin Multiplatform, Android development including ViewModel and WorkManager integration, and offers JSR-330 compatibility for seamless migration from other DI frameworks like Hilt, Dagger, or Guice. Koin Annotations includes compile-time safety checks, automatic type binding detection, and flexible module organization through configurations. It scales from simple single-module applications to complex multi-module architectures with minimal overhead. ``` -------------------------------- ### Declaring a Module with @Module Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/modules.md Shows how to declare a Koin module by annotating a class with `@Module`. It also illustrates how to load this module into Koin using the generated `.module` extension function, requiring the `org.koin.ksp.generated.*` import. ```kotlin @Module class MyModule ``` ```kotlin // Use Koin Generation import org.koin.ksp.generated.* fun main() { startKoin { modules( MyModule().module ) } } ``` -------------------------------- ### Add Kotzilla SDK Dependency Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/monitor.md Adds the Kotzilla SDK core dependency to your project's build file. This is required for performance monitoring. ```kotlin dependencies { implementation "io.kotzilla:kotzilla-core:latest.version" } ``` -------------------------------- ### Inject Lazy Dependency with Lazy Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Koin automatically handles the injection of lazy dependencies. By declaring a constructor parameter of type `Lazy`, Koin will generate the DSL code to use `inject()` instead of `get()`, ensuring the dependency is resolved only when first accessed. ```kotlin import org.koin.core.annotation.Single import org.koin.core.qualifier.inject interface LoggerDataSource @Single class LoggerInMemoryDataSource : LoggerDataSource @Single class LoggerAggregator(val lazyLogger : Lazy) ``` -------------------------------- ### Organize Modules with @Configuration Annotation Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/modules.md The @Configuration annotation is used to group Koin modules into different configurations, such as environments or feature sets. Modules can be assigned to a single default configuration or multiple named configurations. This annotation requires @KoinApplication to be present in the application to scan and load modules from these configurations. ```kotlin // Put module in default Configuration @Module @Configuration class CoreModule // module A @Module @Configuration class ModuleA // module B @Module @Configuration class ModuleB // module App, scan all @Configuration modules @KoinApplication object MyApp // This module is available in both "prod" and "test" configurations @Module @Configuration("prod", "test") class DatabaseModule { @Single fun database() = PostgreSQLDatabase() } // This module is available in default, test, and development @Module @Configuration("default", "test", "development") class LoggingModule { @Single fun logger() = Logger() } // Development-only configuration @Module @Configuration("development") class DevDatabaseModule { @Single fun database() = InMemoryDatabase() } // Production-only configuration @Module @Configuration("production") class ProdDatabaseModule { @Single fun database() = PostgreSQLDatabase() } // Available in multiple environments @Module @Configuration("default", "production", "development") class CoreModuleWithMultipleEnvs { @Single fun logger() = Logger() } // Using Configurations with @KoinApplication @KoinApplication(configurations = ["default", "production"]) class ProductionApp @KoinApplication(configurations = ["default", "development"]) class DevelopmentApp // Load only default configuration (same as @KoinApplication with no parameters) @KoinApplication class SimpleApp ``` -------------------------------- ### Component Scanning with @ComponentScan Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/modules.md Illustrates how to use the `@ComponentScan` annotation on a module class to automatically scan the current package and subpackages for annotated components. It mentions the ability to specify a target package and the cross-Gradle module traversal introduced in version 1.4. ```kotlin @Module @ComponentScan class MyModule // Or specify a package: // @ComponentScan("com.my.package") ``` -------------------------------- ### JSR-330 Compatibility with Kotlin DI Source: https://context7.com/insertkoinio/koin-annotations/llms.txt Demonstrates using standard Jakarta Inject annotations (@Singleton, @Named, @Inject) with Koin for dependency injection in Kotlin. This allows for framework migration and uses Koin's DSL for module definition and retrieval. It showcases cache implementations and a cache manager. ```kotlin import jakarta.inject.Singleton import jakarta.inject.Named import jakarta.inject.Inject interface Cache { fun get(key: String): Any? fun set(key: String, value: Any) } @Singleton @Named("redis") class RedisCache @Inject constructor() : Cache { override fun get(key: String): Any? = null override fun set(key: String, value: Any) {} } @Singleton @Named("memory") class InMemoryCache @Inject constructor() : Cache { private val storage = mutableMapOf() override fun get(key: String) = storage[key] override fun set(key: String, value: Any) { storage[key] = value } } @Singleton class CacheManager @Inject constructor( @Named("redis") private val primaryCache: Cache, @Named("memory") private val fallbackCache: Cache ) { fun getData(key: String): Any? { return primaryCache.get(key) ?: fallbackCache.get(key) } } // Usage - works with JSR-330 annotations import org.koin.ksp.generated.* import org.koin.core.qualifier.named fun main() { startKoin { modules(MyModule().module) } val manager = KoinPlatform.getKoin().get() val redisCache: Cache = get(named("redis")) } ``` -------------------------------- ### Mark External Dependencies with @Provided Source: https://context7.com/insertkoinio/koin-annotations/llms.txt The @Provided annotation signifies that a dependency is supplied externally and should not be subject to compile-time dependency graph checks. This is useful when components rely on instances managed outside the Koin container, such as pre-existing objects or those provided by other systems. The example shows `ExternalAuthProvider` and `SecurityContext` being provided externally. ```kotlin import org.koin.core.annotation.Factory import org.koin.core.annotation.Provided import org.koin.core.annotation.Single // This component is provided by another module or system class ExternalAuthProvider @Single class AuthService(@Provided val externalProvider: ExternalAuthProvider) { fun authenticate(username: String, password: String): Boolean { return externalProvider.validate(username, password) } } @Factory class SecureEndpoint( val authService: AuthService, @Provided val securityContext: SecurityContext ) { fun processRequest(request: Request): Response { if (!securityContext.isAuthorized()) { return Response.unauthorized() } return Response.ok() } } // Usage - external dependencies provided at runtime import org.koin.ksp.generated.* fun main() { val externalAuth = ExternalAuthProvider() startKoin { modules(MyModule().module) } // Provide external components KoinPlatform.getKoin().declare(externalAuth) } ``` -------------------------------- ### Share Platform Component with ContextWrapper Dependency (Kotlin) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/kmp.md Shows how to define an expected 'PlatformComponentA' in commonMain that depends on the 'ContextWrapper'. Platform-specific actual classes are then provided for Android and iOS, demonstrating how the 'ContextWrapper' can be utilized across platforms. ```kotlin // commonMain @Module @ComponentScan("com.jetbrains.kmpapp.native") class NativeModuleA() // package com.jetbrains.kmpapp.native @Factory expect class PlatformComponentA(ctx : ContextWrapper) { fun sayHello() : String } ``` ```kotlin // androidMain // package com.jetbrains.kmpapp.native actual class PlatformComponentA actual constructor(val ctx : ContextWrapper) { actual fun sayHello() : String = "I'm Android - A - with context: ${ctx.context}" } ``` ```kotlin // iOSMain // package com.jetbrains.kmpapp.native actual class PlatformComponentA actual constructor(val ctx : ContextWrapper) { actual fun sayHello() : String = "I'm iOS - A" } ``` -------------------------------- ### Define Factory with @Factory Annotation in Kotlin Source: https://context7.com/insertkoinio/koin-annotations/llms.txt The @Factory annotation marks a class or function to create a new instance every time it's requested from Koin. This is ideal for components that should not be shared and need to be instantiated independently for each usage. Each call to Koin's get() for a factory-annotated type will yield a distinct object. ```kotlin import org.koin.ksp.generated.* import org.koin.core.context.startKoin @Factory class RequestProcessor(val logger: Logger) { fun process(request: Request): Response { logger.log("Processing request: ${request.id}") return Response(request.id, "success") } } @Factory class DataValidator { fun validate(data: String): Boolean = data.isNotEmpty() } fun main() { startKoin { modules(MyModule().module) } val processor1 = KoinPlatform.getKoin().get() val processor2 = KoinPlatform.getKoin().get() // processor1 !== processor2 (different instances) ``` -------------------------------- ### Component Scan Annotation (@ComponentScan) Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/annotations-inventory.md Gathers Koin definitions by scanning packages for annotated classes. Supports scanning the current package or specific packages using string values and glob patterns. ```kotlin import org.koin.core.annotation.ComponentScan // Scan current package @ComponentScan class MyApp // Scan specific packages @ComponentScan("com.example.services", "com.example.repositories") class MyAppWithSpecificPackages // Scan with glob patterns @ComponentScan("com.example.**", "org.app.*.services") class MyAppWithGlobPatterns ``` -------------------------------- ### Scan Packages for Annotated Components with @ComponentScan Source: https://context7.com/insertkoinio/koin-annotations/llms.txt The @ComponentScan annotation enables Koin to automatically discover and include annotated components within specified packages. It supports scanning the current package, specific packages, and using glob patterns for flexible component discovery. ```kotlin import org.koin.core.annotation.Module import org.koin.core.annotation.ComponentScan // Scan current package and subpackages @Module @ComponentScan class CoreModule // Scan specific package @Module @ComponentScan("com.example.services") class ServicesModule // Scan with glob patterns @Module @ComponentScan("com.example.**") // All subpackages class AllServicesModule @Module @ComponentScan("com.example.*.data") // Single-level wildcard class DataLayerModule // Example components that will be scanned package com.example.services import org.koin.core.annotation.Single @Single class EmailService(val config: EmailConfig) { fun sendEmail(to: String, subject: String, body: String) { // Send email implementation } } import org.koin.core.annotation.Factory @Factory class NotificationService(val emailService: EmailService) ``` -------------------------------- ### Configure Koin Annotations Dependencies in Common API Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/kmp.md This snippet illustrates how to include the Koin core and annotations libraries in your common main source set. These are essential for using Koin's dependency injection features and annotation processing. ```kotlin sourceSets { commonMain.dependencies { implementation(libs.koin.core) api(libs.koin.annotations) // ... } } ``` -------------------------------- ### Injecting Qualified Dependency with @Named Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Demonstrates how to inject a dependency that has been qualified using the `@Named` annotation. The `named()` function is used with the `inject()` delegate to retrieve the correctly qualified instance. ```kotlin import org.koin.core.qualifier.named // Assuming LoggerDataSource and LoggerInMemoryDataSource are defined as above // val logger: LoggerDataSource by inject(named("InMemoryLogger")) ``` -------------------------------- ### Add KSP Plugin for Koin Annotations Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/kmp.md This snippet shows how to add the KSP plugin to your project's build script. Ensure the KSP plugin is correctly applied to enable annotation processing for Koin. ```kotlin plugins { alias(libs.plugins.ksp) } ``` -------------------------------- ### Declare Factory with @Factory Annotation Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Declares a class as a Koin factory. Each time an instance of this class is requested, a new instance will be created. This is equivalent to the `factory { }` DSL declaration. ```kotlin import org.koin.core.annotation.Factory @Factory class MyFactoryComponent(val myDependency : MyDependency) ``` -------------------------------- ### Setting up JSR-330 Compatibility in Koin Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Instructions for adding the `koin-jsr330` dependency to your project's build file. This enables the use of Jakarta Inject annotations within your Koin-managed dependency graph. ```kotlin dependencies { implementation "io.insert-koin:koin-jsr330:$koin_version" } ``` -------------------------------- ### Share Expect/Actual Function Definitions with Koin Modules Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/kmp.md This pattern shows how to share definitions by declaring a Koin module in the common code that provides an expected class. Platform-specific actual implementations of the expected class are then provided in native source sets. ```kotlin // commonMain @Module class NativeModuleB() { @Factory fun providesPlatformComponentB() : PlatformComponentB = PlatformComponentB() } expect class PlatformComponentB() { fun sayHello() : String } ``` ```kotlin // androidMain // package com.jetbrains.kmpapp.native actual class PlatformComponentB { actual fun sayHello() : String = "I'm Android - B" } // iOSMain // package com.jetbrains.kmpapp.native actual class PlatformComponentB { actual fun sayHello() : String = "I'm iOS - B" } ``` -------------------------------- ### Resolve Component with Injected Parameters Source: https://github.com/insertkoinio/koin-annotations/blob/main/docs/reference/koin-annotations/definitions.md Demonstrates how to resolve a component that has constructor parameters marked with `@InjectedParam`. The `parametersOf()` function is used with `koin.get()` to pass the required instances during resolution. ```kotlin import org.koin.core.parameter.parametersOf // Assuming MyComponent with @InjectedParam is defined // val m = MyDependency() // val myComponentInstance = koin.get { parametersOf(m) } ```