android - Android Koin DI 无法获取命名实例
问题描述
这是我的代码...
class MainActivity : AppCompatActivity() {
val myService: MyService by inject(named("MyService"))
val yourService: YourService by inject(named("YourService"))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
myService.myServiceDo()
yourService.yourServiceDo()
}
我的应用程序:
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyApp)
module { myModule }
}
}
服务接口:
interface IService {
fun foo()}
我的服务:
class MyService : IService {
override fun foo() {
TODO("Not yet implemented")
}
fun myServiceDo(){
Log.d("MyService", "myServiceDo...")
}
你的服务:
class YourService : IService {
override fun foo() {
TODO("Not yet implemented")
}
fun yourServiceDo() {
Log.d("YourService", "yourServiceDo...")
}
我的模块:
val myModule = module {
single<IService>(named("MyService")) { MyService() }
single<IService>(named("YourService")) { YourService() }
错误就像org.koin.core.error.NoBeanDefFoundException: No definition found for class:'se.jun.koinex.IService' & qualifier:'MyService'. Check your definitions!
即使我确实认为我遵循了 Koin 官方文档,我也无法理解为什么会发生这种情况。
请你帮助我好吗?谢谢。
解决方案
糟糕... startKoin 函数出现错误。对于指定模块,我应该使用模块功能但有一个模块......而且,这里
val myService: MyService by inject(named("MyService"))
val yourService: YourService by inject(named("YourService"))
服务的类型应该是 IService。
如果我想使用 MyService 或 YourService 自己的功能,则应转换为适用的类型。
推荐阅读
- python - 使用 Python 从 HTML 源代码中提取 .jpg
- ios - 声明 NotificationCenter.default.addObserver [swift]
- json - JSON array within an object is not being parsed
- vba - 选择 Word 文档的开头
- angular - 检测Angular 8中不同输入的焦点丢失?
- bash - Ping 子网但使用 bash 跳过范围内的一些 IP
- javascript - 在数组中查找具有特定属性的项目,然后计算有多少,然后使用相应结果的对象创建新数组
- angular - 滚动时,mat-autocomplete 选项下拉菜单不会粘住
- rxjs - 在 rxjs 管道中实现循环逻辑
- reactjs - SharePoint SPFX:无法获取属性“上下文”