我有这个组件:
@Singleton
@Component(modules = OauthModule.class)
public interface OauthComponent {
void inject(LoginActivity a);
}
和模块:
@Module
public class OauthModule {
@Provides
@Singleton
Oauth2Service provideOauth2Service() {
return new Oauth2StaticService();
}
}
这是另一个组件:
@Singleton
@Component(modules = LoggedUserModule.class)
public interface LoggedUserComponent {
void inject(LoginActivity a);
}
我得到这个错误:
Error:(15, 10) error: Oauth2Service cannot be provided without an @Provides- or @Produces-annotated method.
如果我将 LoggedUserComponent
的注入(inject)方法参数更改为另一个 Activity
,则 AnotherActivity
如下所示:
@Singleton
@Component(modules = LoggedUserModule.class)
public interface LoggedUserComponent {
void inject(AnotherActivity a);
}
编译正常。为什么?我不能有两个具有相同注入(inject)签名的组件吗?
我正在尝试了解 Dagger
的工作原理,因此我们将不胜感激。谢谢。
最佳答案
想到dagger
作为一个对象图——它实际上是。您可能不有 2 个不同的组件能够注入(inject)相同的对象,而不是出于测试目的(或者如果您想要包含不同的行为,而不是额外的行为)。
如果您的 LoginActivity
依赖于多个模块,您应该将它们聚合在一个组件中,因为正如您的错误所示,如果 Dagger 无法提供来自单个组件的所有依赖项,它将失败。
@Singleton
@Component(modules = {LoggedUserModule.class, OauthModule.class})
public interface LoggedUserComponent {
void inject(AnotherActivity a);
}
查看Oauth2Service
,这很容易成为多个对象可以使用的东西,因此更高的范围就足够了。在这种情况下,您应该考虑使用 @Singleton
添加它。您的应用程序组件的范围,或者可能创建自己的组件,例如一个@UserScope
.
然后你将不得不制作你的 LoggedUserComponent
一个@Subcomponent
或使用 @Component(dependencies = OauthComponent.class)
将此组件声明为依赖项并在 OauthComponent
中提供 setter/getter 为了它。在这两种情况下,dagger 还能够提供图中较高位置的依赖关系,从而也解决了您的错误。
关于android - Dagger 2 : Error when two components has same inject method signature,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35779851/