【问题标题】:error: [Dagger/MissingBinding] when trying building the project错误:尝试构建项目时 [Dagger/MissingBinding]
【发布时间】:2019-04-23 10:21:18
【问题描述】:

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

错误:[Dagger/MissingBinding] service.KeyStoreService 不能 在没有 @Inject 构造函数或 @Provides-annotated 的情况下提供 方法。 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 上查看了类似的问题,但没有找到任何对我有帮助的东西。

【问题讨论】:

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


    【解决方案1】:

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

    • KeyStoreModulegetKeyStoreService方法的返回类型从KeyStoreServiceInterface改为KeyStoreService
    • ApplicationComponentgetKeyStoreService方法的返回类型从KeyStoreService改为KeyStoreServiceInterface
    • 使用@Binds 注释创建一个抽象方法,该方法将接收KeyStoreService,返回类型将是KeyStoreServiceInterface(为了做到这一点,整个模块应该是抽象的——因此可以创建单独的抽象模块带有@Binds 注释或使KeyStoreModule 抽象并将getKeyStoreService 方法修改为静态)
    • 再次,使用@Binds 注释将KeyStoreService 实例映射到提供的KeyStoreServiceInterface,但在KeyStoreService 构造函数上应用@Inject 注释并通过Dagger 提供密钥库File
    • 不使用@Binds注解,而是在KeyStoreService构造函数上应用@Inject注解并通过Dagger提供密钥库File

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2021-12-13
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多