kosi-libs / Kodein

Painless Kotlin Dependency Injection
https://kosi-libs.org/kodein
MIT License
3.21k stars 174 forks source link

Reduce boiler-plate for binding singletons where all constructors parameters are DI instances #408

Closed rocketraman closed 2 years ago

rocketraman commented 2 years ago

Currently, binding singletons where all the constructor dependencies are coming from Kodein is quite verbose, and requires update every time the number of constructor parameters changes.

It would be nice if there were a shortened syntax to automatically use the primary constructor of a class, passing in the result of instance() for every parameter.

e.g.

// replace
bindSingleton { Foo(instance(), instance(), instance(), instance(), instance()) }
// with something like this
bindSingleton { ::Foo }

This feature is now available in Koin. See https://insert-koin.io/docs/reference/koin-core/dsl-update.

rocketraman commented 2 years ago

Here is a gist that implements this for Kodein, based on the Koin implementation: https://gist.github.com/rocketraman/84302f408d34576052e07589e9e90b26.

romainbsl commented 2 years ago

Hi, This is available with a SNAPSHOT version.

You can use it with le maven repository https://s01.oss.sonatype.org/content/repositories/snapshots/ under the version 8.0.0-ktor-2-SNAPSHOT.

You can now bind with

val di = DI {
   bindSingleton { new(::A) }
   bindSingleton { new(::B) }
}

I would like to introduced an API like

val di = DI {
   bindSingletonOf(::A)
   bindSingletonOf(::B)
}

But I have some crashes with Kotlin/JS and the heavy usage of inlined function typeOf.

rocketraman commented 2 years ago

This is available with a SNAPSHOT version.

Great!

But I have some crashes with Kotlin/JS and the heavy usage of inlined function typeOf.

Hmm, have you reported this to YouTrack? Is that with the IR compiler, or legacy compiler, or both?

romainbsl commented 2 years ago

It is an existing issue, that tackle the problem with a "don't use to many inline functions with typeOf()".

I will need to investigate on this, to know why.