我有一个服务类,我想通过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