dagger 能否根据请求的类型提供不同的接口实现?
Can dagger provide different implementations of the interface, depending on requested type?
刚开始学习Dagger,我在想:它能不能根据需求提供不同的接口实现?
例如,我有一个接口 Api
并且我有这个接口的 2 个实现 - TwitterApi
和 FacebookApi
。我可以这样写吗?
@Provides
Api provideApi(ApiType type) {
switch (type){
case TWITTER_API:
return new TwitterApi();
case FACEBOOK_API:
return new FacebookApi();
}
}
也许 @Named()
能帮上忙?
这实际上取决于您要实现的目标。您有 2 个基本设置,无论您是想同时访问不同的实现,还是只想提供一个。
同时/在同一范围内访问它们
这是您要使用 @Qualifier
的地方,例如@Named
。它允许您定义 2 个相同类型的限定对象,因此您可以在同一模块中同时请求/使用它们。
在这里,您只需在两个实现上加上限定符,即可同时提供和请求两者。
@Binds
@Qualifier("twitter")
Api provideApi(TwitterApi api);
并通过
请求
@Inject @Qualifier("twitter") Api api;
在一个范围内使用一个
如果您有一些 ApiDependentThing
采用您的 Api
实现之一,并且您想提供 TwitterApi
或 FacebookApi
,您可以只绑定一个组件的实现。您可以通过在模块中使用 @Component.Builder
或 @Binds
或其他方式来实现。
使用这种方法,您不会使用限定符,因为您的图表上只有 一个 Api
将在您的组件中使用。
例如只需在您的构建器中绑定一个实例。
@Component
interface ApiComponent {
Api api();
@Component.Builder
interface Builder {
@BindsInstance Builder api(Api api);
ApiComponent build();
}
}
刚开始学习Dagger,我在想:它能不能根据需求提供不同的接口实现?
例如,我有一个接口 Api
并且我有这个接口的 2 个实现 - TwitterApi
和 FacebookApi
。我可以这样写吗?
@Provides
Api provideApi(ApiType type) {
switch (type){
case TWITTER_API:
return new TwitterApi();
case FACEBOOK_API:
return new FacebookApi();
}
}
也许 @Named()
能帮上忙?
这实际上取决于您要实现的目标。您有 2 个基本设置,无论您是想同时访问不同的实现,还是只想提供一个。
同时/在同一范围内访问它们
这是您要使用 @Qualifier
的地方,例如@Named
。它允许您定义 2 个相同类型的限定对象,因此您可以在同一模块中同时请求/使用它们。
在这里,您只需在两个实现上加上限定符,即可同时提供和请求两者。
@Binds
@Qualifier("twitter")
Api provideApi(TwitterApi api);
并通过
请求@Inject @Qualifier("twitter") Api api;
在一个范围内使用一个
如果您有一些 ApiDependentThing
采用您的 Api
实现之一,并且您想提供 TwitterApi
或 FacebookApi
,您可以只绑定一个组件的实现。您可以通过在模块中使用 @Component.Builder
或 @Binds
或其他方式来实现。
使用这种方法,您不会使用限定符,因为您的图表上只有 一个 Api
将在您的组件中使用。
例如只需在您的构建器中绑定一个实例。
@Component
interface ApiComponent {
Api api();
@Component.Builder
interface Builder {
@BindsInstance Builder api(Api api);
ApiComponent build();
}
}