https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
koin
  • v

    vitaliy

    10/22/2020, 2:10 PM
    Hi everybody, I am trying to find a good solution for a following use case without overengineering it: I have generic stuff, that is currently sitting in the root scope. I also have user session-related stuff, which is currently in
    SCOPE_USER
    . This scope is created when user logs in and I close it on logout. There is a custom
    by injectUser()
    function to inject things from this scope for convenience. Question: is it possible to link
    SCOPE_USER
    to root when it is created and close it when user logs out? Or should I rather create another
    SCOPE_GENERAL
    for all the stuff, that is currently in root and then link
    SCOPE_USER
    to it? This would require to inject from a scope -> custom
    by injectGeneric()
    function. Ideally linking stuff to root scope would be ideal, but I do no see a way to do it. Or should I rather keep things as they are? Many thanks for any ideas in advance!
    a
    • 2
    • 6
  • f

    Florian Eula

    10/26/2020, 8:59 AM
    Is there a known source of crashes from the 2.2 RC where the savedstatehandle would not be passed properly ? My module declares a viewmodel as such:
    viewModel { ThingyVM(handle = get(), ...) }
    When injecting it in my fragment, I properly use
    override val viewModel: ThingyVM by viewModel(state = { arguments ?: bundleOf() })
    Sometimes, maybe like one launch out of 30, I get a crash,
    Caused by: org.koin.core.error.NoBeanDefFoundException: No definition found for class:'androidx.lifecycle.SavedStateHandle'. Check your definitions!
            at org.koin.core.scope.Scope.throwDefinitionNotFound(Scope.kt:277)
    t
    a
    • 3
    • 4
  • p

    Patrik Åkerfeldt

    10/29/2020, 12:56 PM
    I'm new to Koin so hopefully I'm just doing something stupid. I have a working Ktor backend service running with Koin but I'm trying to add tests. As soon as I add the dependency
    <dependency>
                <groupId>org.koin</groupId>
                <artifactId>koin-test</artifactId>
                <version>2.2.0-beta-1</version>
                <scope>test</scope>
            </dependency>
    I fail to even start the service with error:
    Kotlin: Cannot access class 'org.koin.core.scope.ScopeInstance'. Check your module classpath for missing or conflicting dependencies
    in all places where I use
    org.koin.ktor.ext.inject
    .
    • 1
    • 2
  • a

    aipok

    10/29/2020, 2:07 PM
    Trying to integrate 2.2.0-beta-3 into my project and interesting if activity is subclass of
    ScopeActivity
    and has field defined like this
    private val splashVM by scope.viewModel<SplashViewModel>()
    it failed with
    Caused by: java.lang.IllegalStateException: Your activity is not yet attached to the Application instance. You can't request ViewModel before onCreate call.
    Am I understand incorrectly that
    by scope.viewModel
    should be called only while I’m calling
    splashVM
    somewhere later in my code? And I only calling
    splashVM
    inside
    onCreate
    but for some reason it still failed and seems to call scope right away on activity init method call. @arnaud.giuliani should I use it somehow differently now?
    a
    • 2
    • 6
  • g

    gps

    11/16/2020, 7:23 AM
    Hi everyone, I'm using Koin with Ktor, and previously I was using Koin in various classes by implementing the
    KoinComponent
    interface, and then using
    inject
    . I don't need to do this if I'm using it in the context of a route, or application, but I think I do need to do this if I'm using it my own classes? After upgrading to Koin 2.2.0 however, I'm getting a warning asking me to add an annotation:
    KoinApiExtension
    . This suggests to me that I'm likely doing something stupid here. Why is it a bad idea for me to implement
    KoinComponent
    ? Thanks!
    a
    i
    • 3
    • 14
  • a

    Archie

    11/18/2020, 9:19 AM
    Hi @arnaud.giuliani, my I ask a question. I found this in the documentation:
    class Presenter(val view : MyViewContract)
    
    val androidModule = module {
    
        scope<MyActivity> {
            // inject current MyActivity
            scoped { Presenter(get()) }
        }
    }
    since the
    activityScope()
    is backed inside the
    ViewModel
    :
    // Create Activity scope (backed by ViewModel)
    override val scope: Scope by lazy { activityScope() }
    And the presenter have the reference of the
    View
    wouldn't this leak the
    Activity
    ? If I understand it correctly, since the
    scope
    is backed inside a
    ViewModel
    the same instance of
    Presenter
    will be provided when the
    Activity
    did some configuration changes (such as device rotation)... The Activity will be destroyed with its views and a new Activity will be created but.. the presenter is still holding the instance of the destroyed view (View of the Old Activity)... I am really confuse.
    a
    • 2
    • 9
  • m

    Moritz Post

    11/18/2020, 10:19 AM
    at the moment i am doing:
    @Composable
      private fun configureNavigation() {
        val navController = rememberNavController()
        loadKoinModules(module { single<NavController> { navController } })
      }
    This has the disadvantage that i have to actively unload the module when the Activity is destroyed.
    g
    • 2
    • 7
  • a

    arnaud.giuliani

    11/18/2020, 1:26 PM
    Don’t use scopes if you don’t really need it. It’s a dagger thing to put scopes everywhere 🙂
    😀 1
    a
    • 2
    • 1
  • a

    arnaud.giuliani

    11/19/2020, 8:41 AM
    So many topics around 🙂 if there is some people with experience that want to help, feel free to ping me 👍 I’ve just started some experiments
    j
    h
    g
    • 4
    • 4
  • h

    holgerbrandl

    11/22/2020, 5:46 PM
    What would be an idiomatic way to pass an Integer via injection using koin? I want to use/inject a counter in different components. I know that a direct pass by ref is not possible (https://stackoverflow.com/questions/51638871/pass-an-integer-by-reference-in-kotlin)
    d
    m
    • 3
    • 5
  • p

    pawegio

    11/25/2020, 2:17 PM
    Hi, after updating koin from 2.1.5 to 2.2.1, I’m no longer able to mock
    MyViewModel
    in android Robolectric UI tests:
    @get:Rule
    val koinTestRule = KoinTestRule.create {
        androidContext(testApplication)
        modules(listOf(
            /* modules */,
            module { viewModel(override = true) { mock<MyViewModel> { /* ... */ } },
        ))
    }
    I use all-open plugin to open view model class for testing purpose (to perform stubbing):
    @AllOpenAnnotation
    class MyViewModel(
       /* ... */
    ) : ViewModel()
    It throws following exception when fragment scenario launches:
    java.lang.NullPointerException
    	at androidx.lifecycle.ViewModel.setTagIfAbsent(ViewModel.java:157)
    	at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:70)
    	at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
    	at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
    	at org.koin.androidx.viewmodel.ViewModelResolverKt.get(ViewModelResolver.kt:23)
    	at org.koin.androidx.viewmodel.ViewModelResolverKt.resolveInstance(ViewModelResolver.kt:12)
    	at org.koin.androidx.viewmodel.scope.ScopeExtKt.getViewModel(ScopeExt.kt:86)
    	at org.koin.androidx.viewmodel.scope.ScopeExtKt.getViewModel(ScopeExt.kt:72)
    	at org.koin.androidx.viewmodel.koin.KoinExtKt.getViewModel(KoinExt.kt:41)
    	at org.koin.androidx.viewmodel.ext.android.FragmentExtKt.getViewModel(FragmentExt.kt:71)
    	at com.xyz.XYZFragment$$special$$inlined$sharedViewModel$2.invoke(SharedViewModelExt.kt:79)
    	at kotlin.UnsafeLazyImpl.getValue(Lazy.kt:81)
    	at com.xyz.XYZFragment.getViewModel(XYZFragment.kt)
    any tips?
    a
    • 2
    • 6
  • o

    oday

    11/30/2020, 10:41 AM
    I guess if I were to provide a getter for this object, the value I’d return is just the name of the object again
    t
    • 2
    • 1
  • d

    deviant

    11/30/2020, 12:06 PM
    hey guys, i have to definitions in my module:
    factory<() -> User>
    factory<() -> Location>
    koin treat it as same type and failed with this exception:
    org.koin.core.error.DefinitionOverrideException: Definition '[Factory:'kotlin.jvm.functions.Function0']' try to override existing definition. Please use override option to fix it
    are there any workarounds?
    f
    j
    • 3
    • 2
  • m

    Mark

    12/04/2020, 3:39 AM
    Any thoughts about using App Startup library to initialize Koin (instead of Application subclass)? https://proandroiddev.com/app-startup-under-the-hood-with-koin-library-example-380e188568ad
    t
    a
    s
    • 4
    • 4
  • m

    Mark

    12/05/2020, 10:29 AM
    How to properly set up and close a
    CoroutineScope
    for a Koin
    Scope
    ?
    s
    • 2
    • 7
  • h

    holgerbrandl

    12/05/2020, 7:11 PM
    Hi, is it possible to resolve generic types with koin? I've tried with
    import org.koin.core.KoinComponent
    import org.koin.core.context.startKoin
    import org.koin.dsl.module
    
    class State<T>(val initialValue: T, name: String? = null)
    
    fun main() {
        val sim = module(createdAtStart = true) {
    
            single{ State("red") }
            single{ State(false) }
        }
    
        startKoin() { modules(sim) }
    
        val koin = (object : KoinComponent {}).getKoin()
        val boolState = koin.get<State<Boolean>>()
        val stringState = koin.get<State<Boolean>>()
    }
    but this fails with
    Exception in thread "main" org.koin.core.error.DefinitionOverrideException: Definition '[Single:'State']' try to override existing definition. Please use override option or check for definition '[Single:'State']'
    t
    d
    • 3
    • 8
  • k

    kenkyee

    12/05/2020, 9:35 PM
    You're better off doing something like: Class Blah : State<Red> Then Single { Blah() }
    👍 1
    h
    • 2
    • 2
  • j

    Joaquim Ley

    12/07/2020, 2:48 PM
    I’m not able to use Koin in a KMM project 😞 really need some help: This is the Koin in the shared module
    fun initKoin(appDeclaration: KoinAppDeclaration = {}): KoinApplication {
      return startKoin {
        appDeclaration()
        modules(domainModule, remoteModule, dataModule)
      }
    }
    
    fun startIosKoin(iosModules: List<Module> = emptyList()) = initKoin {
      modules(iosModules)
    }
    Which is called by KoiniOS.kt
    private val iosModules: List<Module> = listOf(
      storageModule
    )
    
    fun inject() = startIosKoin(iosModules)
    This
    storageModule
    has iOS specific objects such as
    NSDefaults
    Ths domain module has simple kotlin objects as well data module (repository layer) and the remote module is ktor where I have
    expect/actual
    engines. (which is called in the AppDelegate
    KoiniOSKt.inject()
    ) - But for some reason whenever I try to use any use case on iOS it just breaks no
    NoBeanDefFoundException#<init>(kotlin.String){
    Android works fine but iOS can’t use any of the deps, is there something obvious that I am missing or do I need to post more code/plumbing?
    t
    a
    r
    • 4
    • 12
  • s

    Saul Wiggin

    12/15/2020, 3:29 PM
    Still stuck on getting Koin working
    KoinApplication has not been started
    a
    t
    • 3
    • 3
  • d

    deviant

    12/16/2020, 12:18 PM
    guys, are there any helpers to utilize NavArgs from androidx navigation lib? something similar to SavedStateHandle? pass args to viewmodel? maybe SavedStateHandle to NavArgs converter? something like this
    t
    • 2
    • 2
  • t

    timrijckaert

    12/16/2020, 4:58 PM
    Where can I find the most up to date sample which demonstrates Koin in all its glory in an Android app. The official one https://github.com/InsertKoinIO/koin-samples seems a bit out dated 😅
    g
    • 2
    • 1
  • y

    Yasutaka Kawamoto

    12/25/2020, 2:58 AM
    Module#isLoaded is now INTERNAL in 2.2.0, but I want to refer to isLoaded, is there an alternative way? https://github.com/InsertKoinIO/koin/blob/master/CHANGELOG.md#220-beta-2
    👍 2
    a
    • 2
    • 3
  • b

    bobby

    12/29/2020, 1:47 AM
    Hi there, I want to ask a question, is there’s a way to catch an exception that happen during creation of an object inside 
    single{}
     ? The reason I’m asking this is because when creating 
    EncryptedSharedPreferences
     object using 
    single{}
    , sometimes it’s throw an Exception, and I want to catch that, prevent the crash app on user side, thanks
    t
    • 2
    • 5
  • p

    Philipp Mayer

    12/30/2020, 12:50 PM
    Hello everyone, I'd like to ask a question: I currently start using Koin on the Backend with Ktor, and have the following situation:
    fun Application.rooms(db: DB) {
        install(Koin) {
            modules(roomsDI)
        }
    
        val roomFooBar: RoomFooBar by inject()
    
        routing {
            roomRoutes(roomFooBar)
        }
    }
    
    val roomsDI = module {
        single<RoomFooBar> { RoomService(get()) }
        single<RoomRepository> { RoomDatabaseAccessor(???)}
    }
    
    class RoomDatabaseAccessor(private val db: DB) : RoomRepository {...}
    I'm not sure how to pass the
    db
    parameter (which is a function parameter of
    Application.rooms()
    ) into the koin module. The parameter changes depending on the context, so just declaring it inside the
    module { }
    would not work. Any hints for that? I could not really find a satisfying solution in the docs. Thanks a lot!
    f
    • 2
    • 2
  • t

    timrijckaert

    01/03/2021, 9:45 AM
    https://stackoverflow.com/q/65439079/2976366 It would be nice if someone could give a solution to this since it is such a common question and architecture used in Android
    ➕ 2
    e
    • 2
    • 1
  • n

    nrobi

    01/05/2021, 11:24 AM
    Could anyone pinpoint to a working
    KoinTestRule
    example? I’m trying to use
    KoinTestRule.create{ }
    then
    koinTestRule.koin.loadModules()
    to override some bean definitions with mocks, though I’m bumping into:
    java.lang.IllegalStateException: A KoinContext is already started
    • 1
    • 1
  • h

    holgerbrandl

    01/05/2021, 9:08 PM
    Hi there, is it possible to list/iterate all declared instances of a koin instance?
    e
    • 2
    • 2
  • t

    tieskedh

    01/08/2021, 11:50 PM
    Noob question: I am refactoring a single app that is build for multiple organisations. An organisation has various rules.and based upon those rules decisions are made. At this moment a reference to the organisation is passed around almost everywhere. This means that if a new piece of data needs to be passed around, it's very easy to add it to the organisation, which therefor is huge. I read about koin scopes and now is my question: is it possible to use scopes to create classes based upon the current organisation-ID?
    j
    • 2
    • 1
  • k

    Kshitij Patil

    01/16/2021, 2:56 PM
    How to provide android context to
    checkModules()
    test ? I'm getting can't provide null context to Database object as my viewmodel depends on repository which depends on room database. I tried to follow androidx-samples example from repo but failed to get it working
    a
    • 2
    • 6
  • h

    Helio

    01/19/2021, 7:04 AM
    Hello, 👋🏽 I was wondering if this would still be a good manner to inject dependencies using Koin in Top level function. https://stackoverflow.com/a/50840374 Does anyone have a better approach for it?
    t
    a
    • 3
    • 9
Powered by Linen
Title
h

Helio

01/19/2021, 7:04 AM
Hello, 👋🏽 I was wondering if this would still be a good manner to inject dependencies using Koin in Top level function. https://stackoverflow.com/a/50840374 Does anyone have a better approach for it?
t

tynn

01/19/2021, 9:09 AM
I don't think so. Eventually you should create a single instance within your Koin graph instead of using top level functions which require dependencies.
h

Helio

01/19/2021, 9:14 AM
What do you mean is: Wrap up this "top level function" in a class and probably inherit from KoinComponent to allow the injection of the class I want?
a

arnaud.giuliani

01/19/2021, 10:26 AM
You can use directly the global context:
GlobalContext.get().get()
in next Koin version, it will be more
defaultContext().get()
t

tynn

01/19/2021, 10:57 AM
@Helio I acutally meant to use a class with dependencies.
KoinComponent
should not be necessary then.
a

arnaud.giuliani

01/19/2021, 10:59 AM
yep 👍
h

Helio

01/19/2021, 10:04 PM
Hello again, First of all, I would like to thank you both for your quick response. 🙂 • We are currently using Koin 2.2.2 for Ktor. I ended up going with the GlobalContext as suggested by Arnaud, I will try to explain why, even though it might sound confusing (I know how these things are.. haha). Also, it worth saying that we will keep watching for updates. to get rid of the second
get()
. @tynn, in our scenario, we have a Ktor Controller (which is used to declare our apis) and for this specific case we have this “Helper” class, which handle some Generic Top Level functions for us. For example, in our Controller, we have the following
snippet
. There you can see that we are injecting a UseCase class.
fun Route.tokenApi() {
    val createAccessTokenUseCase: CreateAccessTokenUseCase by inject()

    route("/token") {
        post("/build") {
            val buildInfo = call.principal<Principal>().getBuildInfo()
            createAccessTokenUseCase.createBuildToken(buildInfo,
                    TokenatorPermissionGroupProvider.getGroupsFor(call.request.local.uri)).let { call.respond(HttpStatusCode.Created, it) }
        }
}
This line
val buildInfo = call.principal<Principal>().getBuildInfo()
reference our Top level function
getBuildInfo()
. This function will use different classes depending on the
Principal
. The way I was doing before, I was injecting the class I wanted in the Controller context and passing it to my function like this
getBuildInfo(injectedClassForPrincipal1)
. Complete example:
fun Route.tokenApi() {
    val createAccessTokenUseCase: CreateAccessTokenUseCase by inject()
    val myInjectedClassForPrincipalOne: MyInjectedClassForPrincipalOne by inject()
    route("/token") {
        post("/build") {
            val buildInfo = call.principal<Principal>().getBuildInfo(myInjectedClassForPrincipalOne)
            createAccessTokenUseCase.createBuildToken(buildInfo,
                    TokenatorPermissionGroupProvider.getGroupsFor(call.request.local.uri)).let { call.respond(HttpStatusCode.Created, it) }
        }
}
Soon, we will need to make
getBuildInfo()
able to handle a request for a different principal… Which we would need to add another parameter to
getBuildInfo(injectedClassForPrincipal1, injectedClassForPrincipal2)
. Complete example:
fun Route.tokenApi() {
    val createAccessTokenUseCase: CreateAccessTokenUseCase by inject()
    val myInjectedClassForPrincipalOne: MyInjectedClassForPrincipalOne by inject()
    val myInjectedClassForPrincipalTwo: MyInjectedClassForPrincipalTwo by inject()
    route("/token") {
        post("/build") {
            val buildInfo = call.principal<Principal>().getBuildInfo(myInjectedClassForPrincipalOne, myInjectedClassForPrincipalTwo)
            createAccessTokenUseCase.createBuildToken(buildInfo,
                    TokenatorPermissionGroupProvider.getGroupsFor(call.request.local.uri)).let { call.respond(HttpStatusCode.Created, it) }
        }
}
Using the GlobalContext.get().get(), doesn’t make necessary for me to be injecting class by class. I can just reference them in the Top level functions it should be used. Also, IMHO, I don’t think for this scenario it makes sense to let my TokenController knows about (myInjectedClassForPrincipalOne, myInjectedClassForPrincipalTwo). Please, let me know if you think it makes sense or if it doesn’t make sense at all (I’m relative new to Kotlin). Also, I’m always keen to hear different point of views.
a

arnaud.giuliani

01/20/2021, 5:08 PM
yes a bit like compose, it can be a scenario to just inject somewhere at top level a needed instance. Seems ok then 👍
h

Helio

01/20/2021, 8:11 PM
Awesome! Thanks for confirming. :)
View count: 6