我有一个服务类,我想通过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上查看了类似的问题,但没有发现任何对我有帮助的东西。

最佳答案

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


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

07-24 09:49
查看更多