evant / kotlin-inject

Dependency injection lib for kotlin
Apache License 2.0
1.14k stars 51 forks source link

There seem to be no way to define bindings in a separate file (like module for dagger) #402

Closed sergeshustoff closed 1 week ago

sergeshustoff commented 2 weeks ago

Case: Let's say we have a huge app with bloated components and a lot of implementation to interface bindings. When using dagger those bindings are usually extracted to a module. In case of kotlin-inject those bindings have to stay in the controller and bloat it even more.

Solution: Extract bindings to separate component? But that doesn't seem to work

interface Base

@CustomScope
@Inject
class Impl : Base

class BindingsComponent {
    @Provides
    fun bind(impl: Impl): Base = impl
}

@CustomScope
@Component
abstract class MainComponent(
    @Component val bindings: BindingsComponent = BindingsComponent(),
) {
    abstract fun base(): Base
}
vRallev commented 1 week ago

You need to add the interface as super type:

interface Base

@CustomScope
@Inject
class Impl : Base

interface BindingsComponent {
    @Provides
    fun bind(impl: Impl): Base = impl
}

@CustomScope
@Component
abstract class MainComponent : BindingComponent {
    abstract fun base(): Base
}

This should work.

sergeshustoff commented 1 week ago

That works, thanks)