例如我有以下课程:
abstract class BaseClass()
class SpecificClass : BaseClass()
Run Code Online (Sandbox Code Playgroud)
现在,我想SpecificClass通过依赖注入提供,但我也想在同一个图中koin提供基类。BaseClass
需要明确的是,我想做一些类似的事情:
class Someclass {
...
private specificClass: SpecificClass by inject()
...
}
class Someclass {
...
private baseClass: BaseClass by inject()
// where this BaseClass is just the the same instace of the SpecificClass in the dependency graph
...
}
Run Code Online (Sandbox Code Playgroud)
我该如何让我的模块做到这一点?如何将实现实例注入到基类引用中?
您可以通过两种方式使用 Koin 来完成此操作
方法1
您可以像这样为它们创建依赖关系
single {
SpecificClass()
}
single<BaseClass> {
get<SpecificClass>()
}
Run Code Online (Sandbox Code Playgroud)
这样,每当你注入一个实例时,它就会相应地被注入
方法二
您可以像这样使用命名依赖项
single("BaseClassImpl") {
SpecificClass()
}
Run Code Online (Sandbox Code Playgroud)
当您想要注入它时,请为该依赖项提供密钥,如下所示:
class Someclass {
...
private specificClass: SpecificClass by inject("BaseClassImpl")
...
}
class Someclass {
...
private baseClass: BaseClass by inject("BaseClassImpl")
// where this BaseClass is just the the same instace of the SpecificClass in the dependency graph
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2940 次 |
| 最近记录: |