Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplified beans definition #1029

Closed
qwert2603 opened this issue Mar 1, 2021 · 1 comment · Fixed by #1225
Closed

Simplified beans definition #1029

qwert2603 opened this issue Mar 1, 2021 · 1 comment · Fixed by #1225

Comments

@qwert2603
Copy link
Contributor

qwert2603 commented Mar 1, 2021

Hello!

Motivation

One of the advantages of annotations-based DI is that it does not require to edit DI-related code, when parameters are added or removed from @Inject constructor. For example, Daggers consumes such changes automatically. It would be great to add such possibility to Koin.

Solution

One of the possible solutions may look like this:

import org.koin.core.definition.BeanDefinition
import org.koin.core.module.Module
import org.koin.core.qualifier.Qualifier
import org.koin.dsl.module

inline fun <reified T> Module.single(
    crossinline creator: () -> T,
    qualifier: Qualifier? = null,
    createdAtStart: Boolean = false,
    override: Boolean = false,
): BeanDefinition<T> = single(qualifier, createdAtStart, override) {
    creator()
}

inline fun <reified P0, reified T> Module.single(
    crossinline creator: (P0) -> T,
    qualifier: Qualifier? = null,
    createdAtStart: Boolean = false,
    override: Boolean = false,
): BeanDefinition<T> = single(qualifier, createdAtStart, override) {
    creator(get())
}

inline fun <reified P0, reified P1, reified T> Module.single(
    crossinline creator: (P0, P1) -> T,
    qualifier: Qualifier? = null,
    createdAtStart: Boolean = false,
    override: Boolean = false,
): BeanDefinition<T> = single(qualifier, createdAtStart, override) {
    creator(get(), get())
}

class SomeRepo(val argumentOne: Int)

val someModule = module {
    single(::SomeRepo)
}

With such approach we can remove argumentOne from SomeRepo's constructor or add argumentTwo without any changes in Koin's module definition.

The same can be applied to factory, scoped and other BeanDefinition creators. Moreover, it works well with any method references, not only with constructors.

Limitations

But there are limitations. There is no easy way to specify DefinitionParameters or Qualifier of individual dependency of the bean.

Feedback is welcome.

In comments.

@arnaudgiuliani
Copy link
Member

Closing this, as another PR is fixing it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants