kotlin - With Kodein dependency injection, I don't want to pass around kodein instances everywhere -


using kodein, find have pass kodein instances around or inject them modules , classes. have classes disconnected want them able discover "one true kodein". since server side app, , have 1 kodein scope should easy. can create global object, such as:

val kodeinglobal: kodein = kodein { ... } 

but doesn't work when of modules re-used across different projects , cannot share 1 instance. maybe separate module hold global work, need var , i'd prefer not changeable.

can kodein find main, top-level or global scope on own?

note: this question intentionally written , answered author (self-answered questions), idiomatic answers commonly asked kotlin/kodein topics present in so.

in kodein 3.x there new module available called kodein-conf. allows create modifiable instance of kodein (as long modify before first injection done), , contains kodein global instance shared use if desired instead. contrary normal kodein instance must have bindings defined @ construction time , can never modified.

using predefined global easy referencing kodein.global. , works same configurable kodein instance:

kodein.global.addimport(somemodule) // add other modules  val something: somethingcool = kodein.global.instance() // inject 

if want make own global:

val kodeinglobal = configurablekodein() 

for more configurablekodein read kodein 3.x docs configurablekodein, , predefined global instance the god complex: 1 true kodein

as helper, can use new kodeinglobalaware interface have natural access within class kodein instances without having directly reference global kodein instance. example adding interface, can call instance creation methods, such as:

class defaultsomeservice(): someservice, kodeinglobalaware {     val mapper: objectmapper = instance()     // ... } 

or if have case (such testing) want use global instance unless overridden specific instance, can similar to:

class defaultsomeservice(override val kodein: kodein = kodein.global): someservice, kodeinaware {     val mapper: objectmapper = instance()     // ... } 

which uses kodeinaware interface , and overrides abstract member variable kodein same transparent type of injection within class, while defaulting global instance.

if want inject kodein whether global instance or specific one, see: injecting kodein instances within binding declarations alternative.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -