错误:尝试构建项目时出现[Dagger / MissingBinding]

时间:2018-11-20 21:45:43

标签: java android dependency-injection dagger-2 dagger

我有一个服务类,我想通过Dagger提供它。但我在下面看到此错误:

  

错误:[Dagger / MissingBinding] service.KeyStoreService不能为   没有@Inject构造函数或@Provides注释的情况下提供   方法。 service.KeyStoreService在以下位置提供   di.component.ApplicationComponent.getKeyStoreService()

这是我的组件类:

@ApplicationScope
@Component(modules = {ApplicationContextModule.class, KeyStoreModule.class})
public interface ApplicationComponent {

    @ApplicationContext
    Context getApplicationContext();

    KeyStoreService getKeyStoreService();

}

这是我的KeyStoreModule:

@Module(includes = {ApplicationContextModule.class})
public class KeyStoreModule {

    @Provides
    @ApplicationScope
    KeyStoreServiceInterface getKeyStoreService(@ApplicationScope Context context){
        File file = new File(context.getFilesDir(), "keystore/keystore");
        return new KeyStoreService(file);
    }
}

KeyStoreService实现KeyStoreServiceInterface。

这是我启动Dagger2的方式:

public class MyApplication extends Application {

    private ApplicationComponent applicationComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        applicationComponent = DaggerApplicationComponent.builder()
                .applicationContextModule(new ApplicationContextModule(this))
                .build();

    }

}

有人看到它可能出了问题吗?我在Stackoverflow上看过类似的问题,但没有找到任何对我有帮助的东西。

1 个答案:

答案 0 :(得分:2)

这是一件事:Dagger提供基于特定类型的实例。以下是解决此问题的几种方法

  • getKeyStoreService中将KeyStoreServiceInterface方法的返回类型从KeyStoreService更改为KeyStoreModule
  • getKeyStoreService中将KeyStoreService方法的返回类型从KeyStoreServiceInterface更改为ApplicationComponent
  • 创建带有@Binds批注的抽象方法,该方法将接收KeyStoreService,返回类型为KeyStoreServiceInterface(为此,整个模块应该是抽象的-因此可能使用@Binds注释创建单独的抽象模块,或者使KeyStoreModule抽象并修改getKeyStoreService方法为静态)
  • 再次使用@Binds注释将KeyStoreService实例映射到提供的KeyStoreServiceInterface,但在@Inject构造函数上应用KeyStoreService注释并提供密钥库{{1 }}通过Dagger
  • 不使用File批注,而是在@Binds构造函数上应用@Inject批注,并通过Dagger提供密钥存储区KeyStoreService