Hi, in Ktor dependency injection, is it possible t...
# ktor
t
Hi, in Ktor dependency injection, is it possible to override en exiting injection which is register in Application.module()?
b
You'll need something like this in the plugin config:
Copy code
install(DI) {
    conflictPolicy = DependencyConflictPolicy { prev, current ->
        when (val result = DefaultConflictPolicy.resolve(prev, current)) {
            is Conflict -> KeepNew
            else -> result
        }
    }
}
Then you can override dependencies. We should probably have a standard option here for easier config...
👍 1
s
I think it’s
install(DI)
, couldn’t find
DependencyInjection
b
oh yes, sorry 🤦‍♂️
t
when I run testapplication, I got this error
Copy code
Please make sure that you use unique name for the plugin and don't install it twice. Conflicting application plugin is already installed with the same key as `DI`
io.ktor.server.application.DuplicatePluginException: Please make sure that you use unique name for the plugin and don't install it twice. Conflicting application plugin is already installed with the same key as `DI`
	at io.ktor.server.application.ApplicationPluginKt.install(ApplicationPlugin.kt:137)
But this error does not come up when I start up application.
b
it will need to be called before any reference to
dependencies
is called.... if that is already the case, then it could be an issue with it being called from the config file
t
yes, it is not possible to run any dependencies under TestApplication and module() with dependencies. Not sure why it complains about already installed with the same key as ‘DI’
b
oh, for the test application it should automatically work the opposite way - you declare your mocks, then install your modules normally and they will avoid overriding
Copy code
fun test() = testApplication {
  application {
    dependencies.provide<MyService> {
      MockService()
    }
    loadServices()
  }
}
t
so if we have defined this overriding by default, then it will fail under testApplication, but in normal application running it will always override the last injection. Is it possible to have this feature on under test situation so we dont need to turn it off if it is running testApplication?
b
Yeah, the regular plugin install should be able to override this...
Copy code
testApplication {
    install(DI) {
         conflictPolicy = ...
    }
    application {
         // my modules
    }
}
t
but we got the error which said the install(DI) is already registered under module() which we have setup for both normal usage and test usage.
b
you'll have to figure out what else is calling
dependencies
before the install block... you might need to download the ktor sources and add a breakpoint in
io/ktor/server/plugins/di/DependencyInjection.kt
it may be the config file module loading too if you're using that with automatic injection