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