Skip to content

Commit

Permalink
feat: added providers
Browse files Browse the repository at this point in the history
  • Loading branch information
y9san9 committed Dec 22, 2023
1 parent 6f026ff commit 1919707
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
24 changes: 19 additions & 5 deletions core/src/commonMain/kotlin/app/meetacy/di/builder/DIBuilder.kt
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,8 @@ public class DIBuilder(dependencies: Dependencies) {
name: String? = null,
crossinline factory: DI.() -> T
) {
val key = DependencyKey<T>(
type = typeOf<T>(),
name = name
)
val provider = DependencyProvider.Singleton { di -> di.factory() }
register(key, provider)
register<T>(name, provider)
}

public inline fun <reified T> singleton(
Expand All @@ -89,6 +85,24 @@ public class DIBuilder(dependencies: Dependencies) {
)
}

public inline fun <reified T> provider(
name: String? = null,
crossinline factory: DI.() -> T
) {
val provider = DependencyProvider { di -> di.factory() }
register<T>(name, provider)
}

public inline fun <reified T> provider(
noinline factory: DI.() -> T
): DIBuilderProviderDelegate<T> {
return DIBuilderProviderDelegate(
di = this,
type = typeOf<T>(),
factory = factory
)
}

public fun build(): DI = DI(
dependencies = Dependencies(dependencies.toList())
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ public class DIBuilderConstantDelegate<T>(
property: KProperty<*>
): ReadOnlyProperty<Any?, Unit> {
di.register(
key = DependencyKey(
type = type,
name = property.name
),
key = DependencyKey(type, property.name),
provider = { value }
)
return ReadOnlyProperty { _, _ -> }
Expand All @@ -37,12 +34,26 @@ public class DIBuilderSingletonDelegate<T>(
property: KProperty<*>
): ReadOnlyProperty<Any?, Unit> {
di.register(
key = DependencyKey(
type = type,
name = property.name
),
key = DependencyKey(type, property.name),
provider = DependencyProvider.Singleton { di -> di.factory() }
)
return ReadOnlyProperty { _, _ -> }
}
}

public class DIBuilderProviderDelegate<T>(
private val di: DIBuilder,
private val type: KType,
private val factory: DI.() -> T
) {
public operator fun provideDelegate(
thisRef: Any?,
property: KProperty<*>
): ReadOnlyProperty<Any?, Unit> {
di.register(
key = DependencyKey(type, property.name),
provider = { di -> di.factory() }
)
return ReadOnlyProperty { _, _ -> }
}
}

0 comments on commit 1919707

Please sign in to comment.