-
Notifications
You must be signed in to change notification settings - Fork 176
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
Implement new
DSL for Factories instead of Providers only.
#469
Comments
I have implemented a working solution in our repo. @PublishedApi
internal interface ParameterizedNew {
operator fun <T : Any> invoke(t: TypeToken<T>): T
}
@PublishedApi
internal inline fun <reified P : Any, T> DirectDIAware.parameterized(
params: P,
block: ParameterizedNew.() -> T,
) = object : ParameterizedNew {
private val pType = generic<P>()
private var consumed by atomic(false)
@Suppress("UNCHECKED_CAST")
override fun <T : Any> invoke(t: TypeToken<T>): T {
if (consumed || !pType.isAssignableFrom(t)) return directDI.Instance(t, null)
consumed = true
return params as T
}
}.run(block)
@PublishedApi
internal inline fun <reified T : Any> ParameterizedNew.invoke(): T = invoke(generic<T>())
public inline fun <T, reified P : Any, reified P1> DirectDIAware.new(
param: P,
constructor: (P1) -> T,
): T = parameterized(param) { constructor(invoke()) }
public inline fun <T, reified P : Any, reified P1, reified P2> DirectDIAware.new(
param: P,
constructor: (P1, P2) -> T,
): T = parameterized(param) { constructor(invoke(), invoke()) }
// 20 more overloads for new, +22 for factory and 22 for multiton. I'm not sure how accurate it is, as I need to write tests for it when it is going to be moved to the main kodein repo. We will also need to settle on how to handle inheritance in the parameter injection. Using There is also an allocation overhead on each creation of a dependency because of the storage of the atomic The resulting code looks like this: container<_, Params> { new(it, ::UserContainer) } |
Of course PR are welcome ! Just curious, from what library and why are you migrating ? |
Similar to what is requested of Koin, we can implement a
new
andbindFactoryOf
overloads that take not only the di instances into consideration, but also the parameters.The way I envision it to work is:
new
invocation, it creates a holder which will contain flagconsumed
that specifies whether the parameters have been used already.instance
from DI directly, it first checks if a) the type of the argument matches the parameter type, and b) whether the parameters have not yet been consumed. If both aretrue
, it provides parameters and marks them asconsumed
.This results in the same concise syntax
bindFactoryOf
being available for use.Would you like me to open a PR for this feature?
P.S. I apologize for issue spam, we're migrating to Kodein and this is a great opportunity to ensure feature parity with Koin.
The text was updated successfully, but these errors were encountered: