Koin Annotations - help declare Koin definition in a very fast and intuitive way, and generate all underlying Koin DSL for you

Overview

Koin Annotations

The goal of Koin Annotations project is to help declare Koin definition in a very fast and intuitive way, and generate all underlying Koin DSL for you. The goal is to help developer experience to scale and go fast ๐Ÿš€ , thanks to Kotlin Compilers.

Current Version

Here below is the current version:

Warning: while this is still in beta. There can be some breaking changes coming in next releases ๐Ÿ™

koinAnnotations = "1.0.0-beta-1"

Koin 3.2+ is required

Setup

First, setup KSP plugin like this, in your root build.gradle:

plugins {
    id "com.google.devtools.ksp" version "1.6.10-1.0.2"
}

Use the following dependencies in your Gradle dependencies section:

// Koin Annotations
implementation "io.insert-koin:koin-annotations:$koinAnnotations"
// Koin Annotations - Ksp Compiler
ksp "io.insert-koin:koin-ksp-compiler:$koinAnnotations"

On your app add the following to generated source code:

  • On Kotlin project:
sourceSets.main {
    java.srcDirs("build/generated/ksp/main/kotlin")
}
  • on Android project:
android {
  applicationVariants.all { variant ->
          variant.sourceSets.java.each {
              it.srcDirs += "build/generated/ksp/${variant.name}/kotlin"
          }
      }
}

Getting Started

Not familiar with Koin? First take a look at Koin Getting Started

Tag your cpomnents with definition & module annotations, and use the regular Koin API.

// Tag your component to declare a definition
@Single
class MyComponent
// Declare a module and scan for annotations
@Module
@ComponentScan
class MyModule

Use the org.koin.ksp.generated.* import as follow to be able to use generated code:

() }">
// Use Koin Generation
import org.koin.ksp.generated.*

fun main() {
    val koin = startKoin {
        printLogger()
        modules(
          // use your modules here, with generated ".module" extension on Module classes
          MyModule().module
        )
    }

    // Just use your Koin API as regular
    koin.get<MyComponent>()
}

That's it, you can use your new definitions in Koin with the regular Koin API

QuickStart

Below some quickstart apps:

Documentation

Comments
  • Fix Task failed When Same named Module classes exist in project

    Fix Task failed When Same named Module classes exist in project

    example

    org/foo/DatabaseConfig.kt

    package org.foo
    
    @Module
    class DatabaseConfig {
        @Single
        fun mariadb(): String = "this is mariadb"
    } 
    

    will generate this file.

    org/koin/ksp/generated/DatabaseConfig$ORG$FOO.kt

    @file:JvmName("DataBaseConfigGen")
    @file:JvmMultifileClass
    
    package org.koin.ksp.generated
    import org.koin.dsl.*
    
    private val DatabaseConfigModule = module {
        val moduleInstance = org.foo.DatabaseConfig()
        single { moduleInstance.mariadb() }
    }
    
    val org.foo.DatabaseConfig.module : org.koin.core.module.Module get() = DatabaseConfigModule
    

    If you have any better idea to generate file naming strategy. please comment ๐Ÿ™

    Fixes #14

    status:checking 
    opened by aerain 9
  • Fix Issue that When two or more Modules exists in same packages, Only one module created

    Fix Issue that When two or more Modules exists in same packages, Only one module created

    Issue

    The title says it all.

    I guess reason of moduleMap existence is handling ComponentScan annotations. but When moduleMap is initialized. some of modules were lost.

    I think #11 is related to this issue ๐Ÿค”

    status:checking 
    opened by aerain 8
  • Add @GetAll for list dependencies. Fixes gh-37

    Add @GetAll for list dependencies. Fixes gh-37

    If a parameter is of type List, the default behaviour is to fill it with get(). Sometimes a getAll() is required instead. @GetAll provides this possibility.

    type:feature-request status:checking 
    opened by PaulWMR 7
  • The module is not generated by the Koin Annotations

    The module is not generated by the Koin Annotations

    Describe the bug The module is not generated by the Koin Annotations

    To Reproduce Steps to reproduce the behavior:

    I'm trying to add a module for the coroutine dispatcher

    `@Module class CoroutinesDispatcherModule { @Single @Named("DefaultDispatcher") fun defaultDispatcher(): CoroutineDispatcher = Dispatchers.Default

    @Single
    @Named("IoDispatcher")
    fun ioDispatcher(): CoroutineDispatcher = Dispatchers.IO
    
    @Single
    @Named("MainDispatcher")
    fun mainDispatcher(): CoroutineDispatcher = Dispatchers.Main
    

    }`

    Expected behavior How can the coroutine dispatcher module be generated

    Koin project used and used version (please complete the following information): [e.g]: koin_version = '3.2.0-beta-1' koin_ksp_version = "1.0.0-beta-1" ksp = '1.6.10-1.0.4'

    I make a call like this:

    @Single class MealDataSourceImpl( private val mealService: MealService, @Named("ioDispatcher") private val coroutineDispatcher: CoroutineDispatcher )

    type:issue status:checking 
    opened by Egi10 6
  • Generate empty module on multiplatform for common code

    Generate empty module on multiplatform for common code

    Describe the bug

    When a module class is created in common code, but does not have any dependencies, the code fails to compile because .module does not exist.

    To Reproduce

    In common code

    package com.my.package
    
    import org.koin.core.annotation.ComponentScan
    import org.koin.core.annotation.Module
    
    @Module
    @ComponentScan("com.my.package")
    class MyPackageModule
    

    In platform specific code

    package com.my.package.usecase
    
    import org.koin.core.annotation.Single
    
    @Single
    class GetUserUseCaseImpl : GetUserUseCase {
        override fun invoke() = "user"
    }
    

    Back in common

    // Use Koin Generation
    import org.koin.ksp.generated.*
    
    // ...
    
    startKoin {
        modules(MyPackageModule().module)
    }
    

    Then run code generation via ./gradlew kspCommonMainKotlinMetadata

    The file default.kt is generated but empty (that's fine). The file MyPackageModuleGen.kt is missing, so common code is not aware of the extension .module.

    When running the code directly on the targeted platform, the files needed for the platform are all generated correctly (MyPackageModuleGen.kt is created in the correct directory).

    It does not prevent the code from compiling, but it stays red in common code.

    Expected behavior

    Generate usable code for common. Maybe use expect keyword?

    Koin project used and used version (please complete the following information):

    val koinVersion= "3.2.0-beta-1"
    val koinKspVersion= "1.0.0-beta-1"
    id("com.google.devtools.ksp") version "1.6.20-RC-1.0.4"
    

    Additional moduleDefinition Add any other moduleDefinition about the problem here.

    status:checking multiplatform 
    opened by tristancaron 6
  • Unresolved reference: StringQualifier

    Unresolved reference: StringQualifier

    Describe the bug Unresolved reference: StringQualifier when using @Named for constructor parameter in class marked with @Single.

    To Reproduce Steps to reproduce the behavior:

    1. Setup a KMP project
    2. Mark a class with @Single
    3. Mark a constructor parameter with @Named
    4. Build
    5. See error

    Expected behavior Successful build

    Koin project used and used version (please complete the following information): koin-core version 3.2.0-beta-1 koin-ksp 1.0.0-beta-1 ksp version 1.6.10-1.0.4

    type:issue status:accepted 
    opened by jsamse 6
  • ComponentScan as a list of packages

    ComponentScan as a list of packages

    Is your feature request related to a problem? Please describe. I have a multi-model project and the interfaces in project A don't bind in project B

    Describe the solution you'd like Provide an opportunity to specify the packages in ComponentScan annotation

    type:feature-request 
    opened by mr-w1lde 5
  • Unresolved reference org.koin.ksp.generated.*  KMP project

    Unresolved reference org.koin.ksp.generated.* KMP project

    Describe the bug Following the documentation results in a Unresolved reference org.koin.ksp.generated.* in a KMP project

    The only way I was able to fix it is by adding

    dependencies {
        add("kspMetadata", KmpLibrary.koinCompiler)
    }
    

    and manually running the kspKotlinMetadata gradle task.

    To Reproduce Steps to reproduce the behavior:

    1. Create a KMP project
    2. Add koin annotations
    3. Try to build the shared module

    Koin project used and used version (please complete the following information):

    • koin-annotations version 1.0.0-beta-2
    • koin-ksp-compiler version 1.0.0-beta-2

    Additional moduleDefinition Using

    val commonMain by getting {
        ...
         kotlin.srcDirs("build/generated/ksp/commonMain/kotlin")
    }
    
    type:issue status:accepted type:documentation multiplatform 
    opened by nrobi144 4
  • KoinViewModel is not working as expected

    KoinViewModel is not working as expected

    I just switched to koin 3.2 & annots 1.0.0 versions. I'm using it in one of my android library modules. the issue is my viewmodel classes which are annotated with @KoinViewModel are defined as "factory" in autogenerated module files:

    val com_******_presentation_stock_Stock = module {
       factory(qualifier=null) { com.******.presentation.stock.StockViewModel(get(),get(),get(),get(),get(),get(),get()) } binds(arrayOf(androidx.lifecycle.ViewModel::class,androidx.lifecycle.DefaultLifecycleObserver::class,com.******.presentation.util.ViewStateHolder::class))
    }
    
    type:issue 
    opened by ugurcany 3
  • Gradle fails with

    Gradle fails with "Overload resolution ambiguity" errors

    Intro I migrated to Koin 3.2.0 (Koin annotation 1.0.0-beta-2) and started rewriting the code with annotations. The project uses several product flavors. When you run a Gradle, then it displays Overload resolution ambiguity and Conflicting declarations errors for each Build variant, which prevents from getting a working build. I use ./gradlew build --warning-mode allcommand for getting error details (see logs attachment).

    Screenshot 2022-05-27 at 10 47 35

    This is interfering with the normal build process in App Center. How can this be fixed? Thanks

    Error

    > Task :app:compileProdReleaseKotlin
    Execution optimizations have been disabled for task ':app:compileProdReleaseKotlin' to ensure correctness due to the following reasons:
      - Gradle detected a problem with the following location: '/Users/admin/projects/test-koin/app/build/generated/ksp/dev6Debug/kotlin'. Reason: Task ':app:compileProdReleaseKotlin' uses this output of task ':app:kspDev6DebugKotlin' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.4.2/userguide/validation_problems.html#implicit_dependency for more details about this problem.
      - Gradle detected a problem with the following location: '/Users/admin/projects/test-koin/app/build/generated/ksp/dev6Release/kotlin'. Reason: Task ':app:compileProdReleaseKotlin' uses this output of task ':app:kspDev6ReleaseKotlin' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.4.2/userguide/validation_problems.html#implicit_dependency for more details about this problem.
      - Gradle detected a problem with the following location: '/Users/admin/projects/test-koin/app/build/generated/ksp/prodDebug/kotlin'. Reason: Task ':app:compileProdReleaseKotlin' uses this output of task ':app:kspProdDebugKotlin' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.4.2/userguide/validation_problems.html#implicit_dependency for more details about this problem.
    Gradle detected a problem with the following location: '/Users/admin/projects/test-koin/app/build/generated/ksp/dev6Debug/kotlin'. Reason: Task ':app:compileProdReleaseKotlin' uses this output of task ':app:kspDev6DebugKotlin' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.4.2/userguide/validation_problems.html#implicit_dependency for more details about this problem. This behaviour has been deprecated and is scheduled to be removed in Gradle 8.0. Execution optimizations are disabled to ensure correctness. See https://docs.gradle.org/7.4.2/userguide/more_about_tasks.html#sec:up_to_date_checks for more details.
    Gradle detected a problem with the following location: '/Users/admin/projects/test-koin/app/build/generated/ksp/dev6Release/kotlin'. Reason: Task ':app:compileProdReleaseKotlin' uses this output of task ':app:kspDev6ReleaseKotlin' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.4.2/userguide/validation_problems.html#implicit_dependency for more details about this problem. This behaviour has been deprecated and is scheduled to be removed in Gradle 8.0. Execution optimizations are disabled to ensure correctness. See https://docs.gradle.org/7.4.2/userguide/more_about_tasks.html#sec:up_to_date_checks for more details.
    Gradle detected a problem with the following location: '/Users/admin/projects/test-koin/app/build/generated/ksp/prodDebug/kotlin'. Reason: Task ':app:compileProdReleaseKotlin' uses this output of task ':app:kspProdDebugKotlin' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.4.2/userguide/validation_problems.html#implicit_dependency for more details about this problem. This behaviour has been deprecated and is scheduled to be removed in Gradle 8.0. Execution optimizations are disabled to ensure correctness. See https://docs.gradle.org/7.4.2/userguide/more_about_tasks.html#sec:up_to_date_checks for more details.
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/dev6Debug/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (4, 5): Conflicting declarations: public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/dev6Debug/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 42): Conflicting declarations: public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/dev6Debug/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 87): Overload resolution ambiguity: 
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/dev6Release/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (4, 5): Conflicting declarations: public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/dev6Release/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 42): Conflicting declarations: public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/dev6Release/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 87): Overload resolution ambiguity: 
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/prodDebug/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (4, 5): Conflicting declarations: public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/prodDebug/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 42): Conflicting declarations: public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/prodDebug/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 87): Overload resolution ambiguity: 
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/prodRelease/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (4, 5): Conflicting declarations: public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module, public val AppModuleModule: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/prodRelease/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 42): Conflicting declarations: public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module, public val AppModule.module: Module
    e: /Users/admin/projects/test-koin/app/build/generated/ksp/prodRelease/kotlin/org/koin/ksp/generated/AppModuleGen.kt: (61, 87): Overload resolution ambiguity: 
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModuleModule: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    e: /Users/admin/projects/test-koin/app/src/main/java/com/mysite/core/App.kt: (56, 33): Overload resolution ambiguity: 
    public val AppModule.module: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModule.module: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModule.module: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    public val AppModule.module: Module defined in org.koin.ksp.generated in file AppModuleGen.kt
    
    > Task :app:compileProdReleaseKotlin FAILED
    

    build.gradle (root level)

    buildscript {
        ext {
            kotlin_version = '1.6.21'
            nav_version = '2.5.0-beta01'
            input_mask_version = '6.1.0'
        }
        repositories {
            google()
            mavenCentral()
            maven { url "https://jitpack.io" }
        }
        dependencies {
            classpath 'com.google.gms:google-services:4.3.10'
            classpath 'com.android.tools.build:gradle:7.2.0'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
            classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
        }
    }
    
    allprojects {
        repositories {
            google()
            mavenCentral()
            maven { url "https://jitpack.io" }
        }
    
        tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
            kotlinOptions {
                freeCompilerArgs += '-Xopt-in=kotlin.RequiresOptIn'
            }
        }
    }
    
    task clean(type: Delete) {
        delete rootProject.buildDir
    }
    

    build.gradle (app level)

    plugins {
        id 'com.android.application'
        id 'com.google.gms.google-services'
        id 'kotlin-android'
        id 'kotlin-kapt'
        id 'androidx.navigation.safeargs'
        id 'kotlin-parcelize'
        id 'com.google.devtools.ksp' version "1.6.21-1.0.5"
    }
    
    android {
        compileSdkVersion 31
        buildToolsVersion '31.0.0'
        defaultConfig {
            applicationId "com.mysite"
            minSdkVersion 26
            targetSdkVersion 31
            versionCode 1
            versionName "2.1.0"
            testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
            vectorDrawables.useSupportLibrary = true
            manifestPlaceholders = [appAuthRedirectScheme: 'com.mysite']
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }
        flavorDimensions "environment"
        productFlavors {
            dev6 {
                dimension "environment"
                versionNameSuffix "-dev6"
            }
            prod {
                dimension "environment"
                versionNameSuffix "-prod"
            }
        }
        buildFeatures {
            viewBinding true
        }
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_11
            targetCompatibility JavaVersion.VERSION_11
        }
        kotlinOptions {
            jvmTarget = '11'
        }
    
        // For KSP
        applicationVariants.all { variant ->
            variant.sourceSets.java.each {
                it.srcDirs += "build/generated/ksp/${variant.name}/kotlin"
            }
        }
    }
    
    dependencies {
        // Kotlin
        implementation 'androidx.core:core-ktx:1.7.0'
        implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    
        // Core
        implementation 'androidx.appcompat:appcompat:1.4.0'
        implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
        implementation 'com.google.android.material:material:1.4.0'
        implementation 'androidx.activity:activity-ktx:1.4.0'
        implementation 'androidx.fragment:fragment-ktx:1.4.0'
        implementation 'androidx.preference:preference-ktx:1.1.1'
        implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    
        // Navigation
        implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
        implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
        implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"
    
        // Lifecycle
        def lifecycle_version = '2.4.0'
        implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
        implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
        implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
        kapt "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
    
        // Coroutines
        def coroutines_version = '1.6.1'
        implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
        implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
        
        // Ktor
        def ktor_version = '1.6.6'
        implementation "io.ktor:ktor-client-core:$ktor_version"
        implementation "io.ktor:ktor-client-cio:$ktor_version"
        implementation "io.ktor:ktor-client-gson:$ktor_version"
        implementation "io.ktor:ktor-client-logging-jvm:$ktor_version"
    
        // Koin
        def koin_version = '3.2.0'
        def koin_annotations_version = '1.0.0-beta-2'
        implementation "io.insert-koin:koin-android:$koin_version"
        implementation "io.insert-koin:koin-androidx-navigation:$koin_version"
        implementation "io.insert-koin:koin-annotations:$koin_annotations_version"
        ksp "io.insert-koin:koin-ksp-compiler:$koin_annotations_version"
    
        // Room
        def room_version = '2.4.0'
        implementation "androidx.room:room-runtime:$room_version"
        implementation "androidx.room:room-ktx:$room_version"
        kapt "androidx.room:room-compiler:$room_version"
    
        // Timber
        implementation 'com.jakewharton.timber:timber:5.0.1'
    
        // Testing
        testImplementation 'junit:junit:4.13.2'
        androidTestImplementation 'androidx.test.ext:junit:1.1.3'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    }
    

    App.kt

    import org.koin.android.ext.koin.androidContext
    import org.koin.android.ext.koin.androidLogger
    import org.koin.core.context.startKoin
    import org.koin.core.logger.Level
    import org.koin.ksp.generated.module
    
    class App : Application() {
    
        override fun onCreate() {
            super.onCreate()
            initKoin()
        }
    
        private fun initKoin() {
            startKoin {
                androidContext(this@App)
                modules(AppModule().module)
            }
        }
    }
    

    AppModule.kt

    import org.koin.core.annotation.ComponentScan
    import org.koin.core.annotation.Module
    
    @Module
    @ComponentScan("com.mysite")
    class AppModule
    

    logs.zip

    opened by artyom4ek 3
  • Conflicting declarations error for multi variant Android module

    Conflicting declarations error for multi variant Android module

    Describe the bug I have multiple variants in my android lib module. so the code below tries to include all generated files and creates conflict when I switch to a different variant (causing multiple identical generated module classes).

        libraryVariants.all { variant ->
            variant.sourceSets.java.each {
                it.srcDirs += "build/generated/ksp/${variant.name}/kotlin"
            }
        }
    

    To Reproduce Steps to reproduce the behavior:

    1. Have an Android library module with multiple build variants.
    2. Trigger module generation for a variant. (make the project)
    3. Switch to a different variant.
    4. Retrigger module generation again. (make the project again)
    5. You will see "Conflicting declarations..." error.

    Expected behavior The source dirs for a particular variant should only care about its own generated files, not the ones for other variants.

    Koin project used and used version (please complete the following information): koin 3.2, annotations 1.0.0-beta-2

    question 
    opened by ugurcany 3
  • Allow top-level functions to be annotated

    Allow top-level functions to be annotated

    Is your feature request related to a problem? Please describe.

    I have many files that define HttpClients like so:

    // FooHttpClient.kt
    fun buildFooHttpClient(config: FooConfig) = HttpClient(CIO) { /* ... */ }
    
    // BarHttpClient.kt
    fun buildBarHttpClient(config: BarConfig) = HttpClient(CIO) { /* ... */ }
    
    // ...etc
    

    ...and a module like so:

    val httpClientsModule = module {
    	singleOf(::buildFooHttpClient) { named("Foo") }
    	singleOf(::buildBarHttpClient) { named("Bar") }
    	// ...etc
    }
    

    I am porting the codebase to use Koin annotations.

    Describe the solution you'd like

    Analogous to how class definitions work, it seemed logical that I would just annotate the builder functions with @Single(binds = [HttpClient::class]) @Named("Foo"), and then @Module @ComponentScan(...) class HttpClientsModule would pick them up.

    This is not the case. Annotating free standing functions generates no code.

    Describe alternatives you've considered

    I could put all the builder functions as methods to a single class and annotate it as @Module, which works but requires me to keep all the definitions in a single file. There is no way to split that class without involving a lot of boilerplate code, the very kind I try to avoid by using koin-annotations.

    Target Koin project koin-annotations

    opened by JanPokorny 0
  • Fix multiple round pass issue #66

    Fix multiple round pass issue #66

    This PR removes the "stop processing" flag since there might be some code to process that was not available in the first round of ksp processing.

    For example: Koin was able to successfully do a first round, where the compiler found @Module and @ComponentScan. The code was generated and the codeGenerated flag was set to true. The issue is that some other ksp processor did generate a new class during the first round. The new class has @Single annotation, but it was ignored since the codeGenerated flag was shutting further processing down.

    This fix makes the processor able to do multiple rounds on the same symbols and recreating generated modules file contents if necessary.

    Fixes #66

    opened by jakoss 1
  • Multiple round processing is ignoring newly generated files

    Multiple round processing is ignoring newly generated files

    Describe the bug I'm trying to add new feature to another ksp processing library that will automatically generate @Single or @Factory annotation for files that are generated by ksp. But the koin processor does not process those newly generated files and i think the reason is usage of flag codeGenerated here https://github.com/InsertKoinIO/koin-annotations/blob/main/compiler/koin-ksp-compiler/src/jvmMain/kotlin/org/koin/compiler/BuilderProcessor.kt#L32. AFAIK this shouldn't be used like that, because even if the processor is done with all classes from my source it can be still called with new classes that are generated by another ksp processor. Is this flag even necessary? Ksp is automatically filtering classes that are processed. Looking at official example (https://github.com/google/ksp/blob/main/examples/playground/test-processor/src/main/kotlin/BuilderProcessor.kt) the processor should store the list of invalid classes, process the valid ones and then result list of invalid ones so it can be called later with of those classes. I think i can do a PR with that if you're open to my suggestion.

    PS. Do you have tests for generated code?

    To Reproduce Steps to reproduce the behavior:

    1. Create an ksp processor that generates class with @Single annotation
    2. Setup a koin project that tries to use that class by AppModule().module
    3. Project does not comple, module with the configuration for generated class does not get generated

    Project that can be reproduced on: https://github.com/jakoss/kmapper/blob/feature/di-integration/examples/koin/src/main/kotlin/com/syouth/kmapper/koin/Main.kt

    Expected behavior Koin should properly generate injection configuration for code that is generated by another ksp processors

    Koin project used and used version (please complete the following information): koin-ksp-processor version 1.1.0

    opened by jakoss 1
  • Lazy dependency in module

    Lazy dependency in module

    Using DSL I could create dependency in a module like this: single { MyDependency(get(), inject()) } Inject returns kotlin.Lazy so there was a possibility to avoid circular dependencies for example when I have a network interceptor which can perform a network request.

    Using annotations, generated class uses only get() to obtain dependency. Is there any way to force change this to inject()?

    type:feature-request 
    opened by esial 2
  • Skip constructor params that have a default value

    Skip constructor params that have a default value

    Is your feature request related to a problem? Please describe. Some of my dependancies specify a default value for their constructor variables.

    Describe the solution you'd like Would it be possible to skip values that are already instantiated.

    Describe alternatives you've considered Today I have to add additional dependencies to the graph that I would otherwise not have added.

    type:feature-request 
    opened by morganbovi 0
  • injection of android navigationGraph args

    injection of android navigationGraph args

    Is your feature request related to a problem? Please describe. I would like to use koin-annotations to inject ViewModel with android navigationGraph parameters.

    Currently I inject it without annotations:

    viewModel { (args: MainFragmentArgs) -> MainViewModel(MainViewState(args), get()) }
    

    main_navigation_graph.xml

    <fragment
            android:id="@+id/fragment_main"
            android:name="my.app.MainFragment"
            tools:layout="@layout/fragment_main">
    
            <argument
                android:name="data"
                app:argType="string" />
    
        </fragment>
    
    class MainFragment : ... {
        override val viewModel: MainViewModel by viewModel {
            parametersOf(MainFragmentArgs.fromBundle(requireArguments()))
        }
    }
    
    interface ViewState
    
    class MainViewState(args: MainFragmentArgs) : ViewState {
        val data = args.data
    }
    
    abstract class BaseViewModel<VS : ViewState> : ViewModel(), CoroutineScopeOwner, DefaultLifecycleObserver, KoinComponent {}
    
    class MainViewModel(
        override val viewState: MainViewState,
        private val repository: MainRepository
    ) : BaseViewModel<MainViewState>() {
    ...
    }
    

    Describe the solution you'd like With annotation processor I would like to inject Navigation graph args, but I think, that's not possible now, because classes are not annotated by Koin.

    @Factory
    class MainViewState(...
    
    @KoinViewModel
    class MainViewModel(...
    

    So when I use it with this annotations I get:

    org.koin.core.error.InstanceCreationException: Could not create instance for [Factory:'my.app.MainViewModel',binds:my.app.BaseeViewModel]
    Caused by: org.koin.core.error.NoBeanDefFoundException: |- No definition found for class:'my.app.MainViewState'. Check your definitions!
    

    because it can't inject val args: MainFragmentArgs I think, because it's added to viewModel manually now by viewModel { (args: MainFragmentArgs) ->

    I tried to use:

    @Factory(binds = [MainFragmentArgs::class])
    class MainViewState(
    

    and

    class MainViewState(
        @InjectedParam val args: MainFragmentArgs,
    

    but it's not annotated by Koin, so I think, that's still not possible use it in this way.

    question 
    opened by mtrakal 3
Owner
insert-koin.io
All about Koin projects
insert-koin.io
Android Ptrace Inject for all ABIs and all APIs. Help you inject Shared Library on Android.

Android Ptrace Inject ไธญๆ–‡ๅฏไปฅๅ‚่€ƒๆˆ‘็š„ๆณจ้‡Šๅ†…ๅฎน่ฟ›่กŒ็†่งฃ ๆˆ‘ๅ†™็š„ๆณจ้‡Š็›ธๅฏนๆฅ่ฏดๆฏ”่พƒๅ…จ้ขไบ† How to build Make sure you have CMake and Ninja in your PATH Edit CMakeLists.txt. Set ANDROID_ND

SsageParuders 65 Dec 19, 2022
Playground project for Koin Koin Compiler - Sandbox

Koin Compiler - Sandbox The goal of Koin compiler & Annotations project is to help declare Koin definition in a very fast and intuitive way, and gener

insert-koin.io 17 Nov 22, 2021
Kotlin-client-dsl - A kotlin-based dsl project for a (Client) -> (Plugin) styled program

kotlin-client-dsl a kotlin-based dsl project for a (Client) -> (Plugin) styled p

jackson 3 Dec 10, 2022
Android library that creates app shortcuts from annotations

Shortbread Android library that generates app shortcuts for activities and methods annotated with @Shortcut. No need to touch the manifest, create XML

Matthias Robbers 1.8k Dec 30, 2022
A simple Kotlin multi-platform abstraction around the javax.inject annotations.

Inject A simple Kotlin multi-platform abstraction around the javax.inject annotations. This allows using the annotations in Kotlin common code so that

Christopher 43 Aug 17, 2022
Kotlin-native webserver for simple image annotations

Kotlin-native webserver for simple image annotations

null 1 Feb 26, 2022
๐Ÿ‘‹ A common toolkit (utils) โš’๏ธ built to help you further reduce Kotlin boilerplate code and improve development efficiency. Do you think 'kotlin-stdlib' or 'android-ktx' is not sweet enough? You need this! ๐Ÿญ

Toolkit [ ?? Work in progress โ› ?? ??๏ธ ?? ] Snapshot version: repositories { maven("https://s01.oss.sonatype.org/content/repositories/snapshots") }

ๅ‡› 35 Jul 23, 2022
A simple and easy adapter for RecyclerView. You don't have to make adapters and view holders anymore. Slush will help you.

ํ•œ๊ตญ์–ด No more boilerplate adapters and view holders. Slush will make using RecyclerView easy and fast. The goal of this project is to make RecyclerView,

SeungHyun 26 Sep 13, 2022
AsyncSport - AsyncSports Async sports is very simple application that shows athletes video feeds

AsyncLabs Interview Solution ?? Writing AsyncLabs Interview Solution App using A

David Innocent 0 Jan 7, 2022
Very simple Kotlin caching library

Very simple Kotlin caching library

Ji Sungbin 4 Jun 15, 2022
This library is a set of simple wrapper classes that are aimed to help you easily access android device information.

SysInfo Simple, single class wrapper to get device information from an android device. This library provides an easy way to access all the device info

Klejvi Kapaj 7 Dec 27, 2022
Example mod with Mixin to help you to get started with creating a mod with mixins.

ExampleMixinMod Example mod with Mixin to help you to get started with creating a mod with mixins. For usage of mixins, see here. Also, remember to tu

null 0 Dec 16, 2021
Auto-generate the fastest possible Parcelable implementations for Java and Kotlin

This project is deprecated It will still be maintained, but no new features will be added. Please use Parcelize, as it is the official way of generati

Bradley Campbell 492 Nov 17, 2022
This program will read from your android application string.xml file and generate translated strings.xml files in your preferred languages using google sheet.

Localize your application content This program will read from your application string.xml file and generate translated strings.xml files in your prefe

DhiWise 4 Jul 29, 2022
This is a Kotlin multiplatform template project used to generate and deploy a natively compiled AWS lambda function using the custom runtime.

Overview This is a Kotlin multiplatform template project used to generate and deploy a natively compiled AWS Lambda function using a custom runtime. U

Greg Steckman 5 Jun 25, 2022
A Gradle plugin for Kotlin Multiplatform projects that generate a XCFramework for Apple targets or a FatFramework for iOS targets, and manages the publishing process in a CocoaPod Repository.

KMP Framework Bundler KMP Framework Bundler is a Gradle plugin for Kotlin Multiplatform projects that generate a XCFramework for Apple targets or a Fa

Marco Gomiero 17 Oct 29, 2022
๐Ÿ’ซ A Gradle Plugin to generate your networking code from Swagger

Swagger Gradle Codegen A Gradle plugin to generate networking code from a Swagger spec file. This plugin wraps swagger-codegen, and exposes a configur

Yelp.com 399 Nov 28, 2022
[prototype] Generate TypeScript interfaces from Kotlin classes

Kotlinx Serialization TypeScript Generator Kotlinx Serialization TypeScript Generator creates TypeScript interfaces from Kotlinx Serialization classes

null 17 Dec 18, 2022
KmMScientists is a Kotlin multiplatform app with swift ui, jetpack compose, koin and realm

KmMScientists KmMScientists is a Kotlin multiplatform app built with swift ui, jetpack compose, koin and realm. Whats Shared? Local Data Persistence w

Kashif Mehmood 20 Dec 27, 2022