我正在尝试使用Toothpick库进行依赖注入,它看起来比其他的更容易使用和测试。
但是当我运行代码时,我遇到了一个问题,Toothpick没有注入任何东西。我现在正在使用它,有点难以弄明白。
我使用的是Kotlin,Android Studio 2.3.3和Gradle 2.3.3,这是我的代码:
的build.gradle
//KOTLIN_VERSION=1.1.4
//TOOTHPICK_VERSION=1.0.8
compile "com.github.stephanenicolas.toothpick:toothpick-runtime:$TOOTHPICK_VERSION"
compile "com.github.stephanenicolas.toothpick:smoothie:$TOOTHPICK_VERSION"
kapt "com.github.stephanenicolas.toothpick:toothpick-compiler:$TOOTHPICK_VERSION"
class AppModule : Module {
constructor(application: Application) {
bind(QuestionRepository::class.java).toInstance(QuestionRepository(application))
}
}
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
setupInjector()
}
fun setupInjector() {
val appScope = Toothpick.openScope(this)
appScope.installModules(SmoothieApplicationModule(this), AppModule(this))
if (BuildConfig.DEBUG) {
Toothpick.setConfiguration(Configuration.forDevelopment());
}
}
}
class MainViewModule : Module {
constructor() {
bind(MainPresenter::class.java).to(MainPresenter::class.java)
}
}
class QuestionRepository @Inject constructor(application: Application) {
val assetManager: AssetManager = application.assets
//a couple of functions
}
class MainActivity : AppCompatActivity(), MainView,
NavigationView.OnNavigationItemSelectedListener {
@Inject lateinit var presenter: MainPresenter
lateinit private var activityScope: Scope
val binding: ActivityMainBinding by lazy {
DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
}
override fun onCreate(savedInstanceState: Bundle?) {
setUpInject()
super.onCreate(savedInstanceState)
setUpView()
}
override fun onDestroy() {
Toothpick.closeScope(activityScope)
super.onDestroy()
}
fun setUpInject() {
activityScope = Toothpick.openScopes(application, this)
activityScope.installModules(MainViewModule())
Toothpick.inject(this, activityScope)
//println(activityScope.toString())
presenter.onAttachView(this)
}
fun setUpView() {
//
}
//Omit implemented method of OnNavigationItemSelectedListener
}
class MainPresenter @Inject constructor() {}
错误讯息:
kotlin.UninitializedPropertyAccessException: lateinit property presenter has not been initialized
在MainActivity中打印activityScope时显示:
Providers: [com.ispark.app.MainPresenter,toothpick.Scope]
当我检查KotlinWeather示例时,代码没有在活动中安装任何模块但仍然注入依赖项。我不明白它是如何运作的。 无论如何,我对Toothpick很新,我错过了什么?
感谢您的帮助。
在build.gradle中,我将kapt替换为annotationProcessor&#34; com.github.stephanenicolas.toothpick:toothpick-compiler:$ TOOTHPICK_VERSION&#34;但仍然相同。
AndroidBinding库是否存在任何问题?
activityScope日志不适用于activityScope,但它是从Toothpick登录的。 activityScope是activityScope:com.ispark.app.MainActivity@2a0e3388:303497268
答案 0 :(得分:1)
您需要确保在使用演示者的代码中调用Toothpick.inject(this,scope)。有一些您正在使用的代码示例也会有所帮助。我还建议检查牙签项目的示例代码,它应该让你去。您还需要创建范围,或检索用于进样的现有范围。