Dagger - 在没有 @Inject 的情况下以最小的仪式注册 class
Dagger - Register class without @Inject with minimal ceremony
假设我想用 Dagger 注册一个 class,它在构造函数上没有 @Inject
注释,并且在其构造函数中也有依赖项。
即
// Java
class MyClass {
public MyClass(MyDependency dependency) { ... }
}
// Kotlin
class MyClass(private val dependency: MyDependency) { ... }
有没有办法注册这个 class 而不必手动将依赖项连接到构造函数中?
// This is how I currently do it. I must list all constructor dependencies
// and then pass them through to the constructor by hand
@Provides
public MyClass getMyClass(MyDependency depdencency) {
return new MyClass(dependency);
}
// Something like this is how I'd like to do it
// In this case, the class is registered _as if_ it had the @Inject on the constructor
@ProvideEvenWithoutAnInject
public abstract MyClass getMyClass();
Dagger 是否提供类似于上面显示的 @ProvideEvenWithoutAnInject
注释的内容?
如果您不能在构造函数上添加 @Inject
注释,则 Dagger 无法为您创建对象。您需要对模块使用 @Provides
注释方法或对您的组件使用 @BindsInstance
来添加它。 (或者,如果您需要更多额外步骤,则作为提供方法的组件依赖项)
假设我想用 Dagger 注册一个 class,它在构造函数上没有 @Inject
注释,并且在其构造函数中也有依赖项。
即
// Java
class MyClass {
public MyClass(MyDependency dependency) { ... }
}
// Kotlin
class MyClass(private val dependency: MyDependency) { ... }
有没有办法注册这个 class 而不必手动将依赖项连接到构造函数中?
// This is how I currently do it. I must list all constructor dependencies
// and then pass them through to the constructor by hand
@Provides
public MyClass getMyClass(MyDependency depdencency) {
return new MyClass(dependency);
}
// Something like this is how I'd like to do it
// In this case, the class is registered _as if_ it had the @Inject on the constructor
@ProvideEvenWithoutAnInject
public abstract MyClass getMyClass();
Dagger 是否提供类似于上面显示的 @ProvideEvenWithoutAnInject
注释的内容?
如果您不能在构造函数上添加 @Inject
注释,则 Dagger 无法为您创建对象。您需要对模块使用 @Provides
注释方法或对您的组件使用 @BindsInstance
来添加它。 (或者,如果您需要更多额外步骤,则作为提供方法的组件依赖项)