kotlin - 使用 Dagger 提供没有接口的实例
问题描述
有一种方法可以在没有实际构造函数调用的情况下提供实例。
class ModelImpl @Inject constructor(...): Model{}
@Provides
fun model(inst: ModelImpl): Model = inst
如果没有接口,有没有办法做同样的事情?Dagger
已经知道 的所有依赖项ModelImpl
,因此它可以创建一个实例。
这显然给出了依赖循环:
@Provides
fun model(inst: ModelImpl): ModelImpl = inst
解决方案
当您使用构造函数注入时,Dagger 可以为您构造对象,并且您已经在使用 Dagger 创建ModelImpl
以将其用作Model
示例中的绑定!
class ModelImpl @Inject constructor(...): Model{}
@Provides
fun model(inst: ModelImpl): Model = inst
// somewhere else...
// both variants would work!
@Inject lateinit var modelImpl : ModelImpl
@Inject lateinit var model : Model
没有接口也一样
class ModelImpl @Inject constructor(...)
// somewhere else...
@Inject lateinit var model : ModelImpl
如果您注释构造函数,那么 Dagger 可以为您创建对象(如果可以解决所有依赖项)。无论您请求对象/依赖项,这都是一样的,
- 作为带
@Provides
注释的方法中的参数(作为您的示例) - 作为字段注入属性 (
@Inject lateinit var
) - 作为另一个对象构造函数中的参数
- 作为组件中的提供方法 (
fun getFoo() : Foo
)
以下所有方法都可以
// foo and bar can both be constructor injected
class Foo @Inject constructor()
class BarImpl @Inject constructor(val foo : Foo) : Bar
@Module
interface BarModule() {
@Binds // you should prefer Binds over Provides if you don't need initialization
// barImpl can be constructor injected, so it can be requested/bound to its interface here
fun bindBar(bar : BarImpl) : Bar
}
@Component(modules = BarModule::class)
interface BarComponent {
fun getBar() : Bar // returns barImpl due to binding
}
@Inject lateinit var bar : BarImpl // but we could as well use the implementation directly
@Inject lateinit var bar : Foo // or just foo
我建议您从一个小示例开始,然后编译项目并查看生成的代码。如果出现问题,您将立即收到错误,同时您可以四处玩耍并尝试不同的设置!
推荐阅读
- javascript - React Router history.push 无限循环
- sql - 当我更改顺序时,SQL 左连接多个表连接性能问题
- android - 为什么我无法解析工件?无法解析配置“:classpath”的所有工件
- objective-c - WKWebview 经常崩溃
- xamarin.android - 我应该在作为参数传递给事件处理程序的 Java.Lang.Object 对象上调用 Dispose() 吗?
- javascript - 如何在每个元素的对象数组中将第一个键值乘以第二个键值,然后删除第二个键?
- sql - 如何从 PL/SQL for 循环中获取旧变量值?
- firebase - 没有电子邮件的 Firebase 身份验证
- mongodb - MongoDB errmsg:“无法从缺少的 BSON 类型转换为日期”
- android - 当收到 FCM 通知而不点击 Android 上的通知时,颤振打开应用程序,如 whatsapp