首页 > 解决方案 > 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 官方文档,我也无法理解为什么会发生这种情况。

请你帮助我好吗?谢谢。

标签: androiddependency-injectionkoin

解决方案


糟糕... startKoin 函数出现错误。对于指定模块,我应该使用模块功能但有一个模块......而且,这里

val myService: MyService by inject(named("MyService"))
val yourService: YourService by inject(named("YourService")) 

服务的类型应该是 IService。

如果我想使用 MyService 或 YourService 自己的功能,则应转换为适用的类型。


推荐阅读