Dagger2不能在andorid中工作
我有使用Dagger2的问题
我创建组件,模块,提供
class testModule { @Provides @Singleton fun provideTestServer(): TestService { } }
我在MainActivity中调用了onCreate()
DaggerImageComponent.builder().build().inject(this)
这里是我的问题DI在MainActivity中正常工作
class MainActivity: AppCompatActivity { @Inject lateinit var testService: TestService }
但其他文件不工作。
object TestObject { @Inject @JvmSynthetic // error: static field cannot inject lateinit var testService: TestService fun test() = testService.testfun() }
要么
@Singleton class TestClass { @Inject lateinit var testService: TestService fun test() = testService.testfun() }
TestClass和TestObject获取错误 – lateinit属性testInterface尚未初始化
我不明白为什么TestClass,TestObject发生错误。
你应该在需要注入变量的类中调用“inject”。 你为MainActivity做了,但你也应该注入你的组件在其他类。 顺便说一下,你有TestClass,看起来你也使用它在客户端代码注入,因为它有“Singleton”注释。 如果这是真的 – 你可以简单地在你的模块中添加提供者,并将其作为一个构造器参数传递给服务器:
class testModule { @Provides @Singleton fun provideTestServer(): TestService { } @Provides @Singleton fun provideTestServer(testService: TestService): TestClass { } }
那么,你的TestClass应该有构造函数:
class TestClass(var testService: TestService) { fun test() = testService.testfun() }
我建议你再读一遍关于匕首,查看本教程: http : //www.vogella.com/tutorials/Dagger/article.html