匕首依赖注入的主要功能



我正在从kotlin代码中的主函数调用类S3FileOperationsAdapter中的一个函数。我正在主函数文件中注入类S3FileOperationsAdapter。所以看起来像

class Runner {
@set:Inject
lateinit var s3FileOperationsAdapter: S3FileOperationsAdapter
fun main(args: Array<String>) {
s3FileOperationsAdapter.readFunction()
}
}

现在的问题是:

  • 当我尝试运行上面的代码时,我得到了错误Error: Main method is not static in class com.amazon.bram.sim.BatchJobRunner, please define the main method as:。这是可以理解的

并且我们只能在kotlin中的对象内生成一个静态函数。因此,在执行此操作时,我无法注入依赖项,因为Dagger does not support injection into Kotlin objects。所以感觉像是陷入僵局。

我的问题是,无论如何,我都想在这个文件中注入依赖项,这样我就可以调用相应的函数。我从";fun main(("在科特林。我怎样才能做到这一点?以前有人面对过这种情况吗?

为了在Dagger中注入任何东西,您必须首先创建组件的实例。由于在fun main()之前根本不会运行任何代码,因此这需要在main本身(或在字段初始化器中(执行。

创建组件的实例后,可以直接向它请求S3FileOperationsAdapter的实例。

fun main(args: Array<String>) {
// Create the component.
val component = DaggerMyComponent.create()
// or use the Component.Builder or Component.Factory you defined for MyComponent.
// Get an object from the component.
// This method should be defined in your component interface.
val adapter = component.s3FileOperationsAdapter()
// Use the object.
adapter.readFunction()
}

如果实际的代码更复杂,有多个注入的对象和更长的main()函数,这可能会有点笨拙。在这种情况下,您可以将当前的main()提取到它自己的类中,并让Dagger在main()中提供该类。

最新更新