android - Dagger 2 : Error when two components has same inject method signature

标签 android dagger-2

我有这个组件:

@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/

相关文章:

android - 如何在 android java 中使用 Dagger2 将 SharedPreferences 注入(inject) ViewModel

java - Dagger 2 : How to inject Map<Class<? extends Foo>, Provider<?扩展 Foo>>

Android MVP + Google Dagger 2 + SQLite

java - 提供两个相同类型的不同实例

android - 启动时无法在 Android 应用程序中实例化 fragment

android - ADB - 未找到设备

android - 构建android应用程序包时如何修复 'Title for on-demand module is missing'?

android - ConstraintLayout 按钮居中,大小为 ViewPager 的 1/3

android - 设计TextView和ImageView的 View 组合

android - Dagger 2 for Android 不是 DI 框架,而是美化了的 Service Locator 吗?