我正在尝试用于依赖注入的牙签库,它看起来比其他的更容易使用和测试。牙签不注入依赖关系
但是我在运行代码时遇到了问题,牙签没有注入任何东西。我现在只是使用它,并且很难弄清楚。
我使用科特林,安卓2.3.3工作室和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示例时,代码没有在活动中安装任何模块,但仍然注入依赖关系。我不明白它是如何工作的。 无论如何,我对牙签相当陌生,我错过了什么?
感谢您的帮助。
EDIT1:
在的build.gradle,我更换annotationProcessor kapt “com.github.stephanenicolas.toothpick:牙签编译:$ TOOTHPICK_VERSION”,但仍然相同。
AndroidBinding库有没有可能的问题?
EDIT2:
activityScope日志不是为activityScope,但它是从牙签日志。 activityScope is activityScope:[email protected]:303497268
你加“kapt { generateStubs =真 参数{ ARG( “toothpick_registry_package_name”, “weather.ekamp.com.weatherappkotlin”) ARG( “toothpick_registry_children_package_names”, “toothpick.smoothie”) } }'这在你的build.gradle? – Anthony
你应该保持kapt,这是kotlin和annotationProcessor不是 – Anthony
@Anthoy,谢谢你的回复。我已经删除了所有的牙签设置并且不再使用它,但是我仍然在build.gradle中设置了kapt并记住我也有参数设置。当我有空时,我会再试一次。再次感谢。 – sunghun