如何在Koin中使用装饰器进行条件覆盖

问题描述

根据某个系统属性是否设置为true,我需要用原始对象的修饰版本覆盖另一个Koin模块中的定义。

这是我要开始工作的代码

interface Service {
  fun doWork()
}

// marker interface for resolving the original instance
interface ServiceInner : Service

// implementation of the decorator
class ServiceDecorator(val delegate: ServiceInner) {
  // skipped delegation logic here
}

// the original module
module {
  single<Service> { ServiceImpl() } bind ServiceInner::class // point 1
}

// the overriding module
module(override = true) {
  single<Service> {
    if (getProperty("override.flag").toBoolean()) {
      ServiceDecorator(get()) // point 2
    } else {
      // what Now? -- point 3
    }
  }
}

代码无法正常工作,而我确实不满意可以正常工作的部分。

首先,我必须定义一个标记接口并将服务的内部实现绑定到它(上面的第1点),以避免在实例化装饰器(上面的第2点)时出错。如果ServiceDecorator构造函数只希望实现Service,Koin将尝试递归实例化该装饰器,直到其耗尽堆栈内存为止。

第二,也是最关键的一点,我不确定在上面的第3点返回什么,因为我根本不想让定义发生。有人认为应该可以检查装饰器的single定义之外的替代标志,但是由于在该上下文中似乎还没有创建范围,因此尚不清楚如何访问属性。 / p>

在Koin中创建条件装饰覆盖的正确方法是什么?

更新

通过使覆盖定义看起来像以下代码,我使代码工作了:

single<Service> {
  if (getProperty("override.flag").toBoolean()) {
    ServiceDecorator(get())
  } else {
    get(ServiceInner::class)
  }
}

在未设置标志的情况下,这有效地重用了原始定义作为其自身的替代。这不是防弹的,因为如果我也想将装饰器实例绑定到另一个接口,那么如果内部接口没有实现它,那将是不可能的,所以仍在寻找更好的选择!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)