android - Dagger如何注入(inject)多个构造函数

标签 android dependency-injection mvp dagger

例如:

class A{
  B b;
  C c;
  @Inject
  A(B b){
    this.b = b;
  }
  @Inject
  A(C c){
    this.c = c;
  }
}

在其中一个模块中:

@Module
public class BModule {

private final B b;
public BModule(B b){
    this.b = b;
}

@Provides
BInterface provideB(){
    return b;
}
}

但是我收到错误,无法在类中注入(inject)两个构造函数,我应该怎么处理这个问题?谢谢!

最佳答案

类只被构造一次;两个构造函数永远不会在同一个实例上同时调用,因此有两个带有 @Inject 注释的构造函数意味着 Dagger 必须选择一个。 你想用这两个带注释的构造函数来完成什么行为?

理想情况下,结合构造函数。

@Inject
A(B b, C c){
  this.b = b;
  this.c = c;
}

或者将其中之一切换为method injection如果绝对必要:

@Inject
A(B b){
  this.b = b;
}
@Inject
void initialize(C c){ // Dagger calls this automatically
  this.c = c;
}

关于android - Dagger如何注入(inject)多个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539356/

相关文章:

php - INSERT Row If Does Not Exist mysql with POST 插入行

Android studio gradle,错误: Cause: error=2, No such file or directory

android - 密码验证应接受特殊字符、数字、字符,但不接受空格

c# - WPF C# MVC/MVP 模式和用户控制代码隐藏

asp.net-mvc - 为什么微软为 ASP.NET 选择 MVC?

android - Dagger2,同时提供不同API的Retrofit实例

java - Android WebView 加载失败(net::ERR_CLEARTEXT_NOT_PERMITTED)

c# - EF 6 的工作单元和依赖注入(inject)设计问题

c# - 如何将 HttpClientFactory 与 AutoRest 生成的客户端一起使用

dependency-injection - 如何使用 CDI 注入(inject)带有参数化构造函数的类的实例(仅限 Java EE 6)