Rafal
04/04/2023, 10:58 AMScope
that way
private val Scope.bffApiKey: String
get() = get(named(BFF_API_KEY))
single {
ApiClass(
apiKey=bffApiKey,
)
}
Matt Rea
04/04/2023, 8:30 PMAdam Brown
04/05/2023, 4:03 AMval mainModule = module {
...
// This is a scope that is created & destroyed, possibly multiple times during lifetime of process
scope<ProjectDefScope> {
// IdRepositoryOkio takes in a `ProjectDef` as a ctor argument
scopedOf(::IdRepositoryOkio) bind IdRepository::class
}
}
ProjectDef
is the thing I care about, it is injected via constructor. Each one of the things injected in this scope inherit from ProjectScoped
abstract class IdRepository(private val projectDef: ProjectDef) : ProjectScoped {
override val projectScope = ProjectDefScope(projectDef)
// This custom inject does the work
private val projectSynchronizer: ClientProjectSynchronizer by projectInject()
...
And then I have the ext function projectInject
that grabs the projectDef
and passes it as an argument to the inject
call.
interface ProjectScoped : KoinComponent {
val projectScope: ProjectDefScope
}
/**
* Injects objects from the Project Scope which all require a ProjectDef
* parameter during injection.
*/
inline fun <reified T : Any> ProjectScoped.projectInject(
qualifier: Qualifier? = null,
mode: LazyThreadSafetyMode = KoinPlatformTools.defaultLazyMode(),
noinline parameters: ParametersDefinition? = null
): Lazy<T> =
lazy(mode) {
val newParameters = if (parameters != null) {
val params = parameters()
parametersOf(arrayOf(params.values.toMutableList().add(projectScope.projectDef)))
} else {
parametersOf(projectScope.projectDef)
}
projectScope.get<T>(qualifier) { newParameters }
}