【问题标题】:Dagger 2 extending interfaces vs dependent componentsDagger 2 扩展接口与依赖组件
【发布时间】:2018-04-11 07:25:27
【问题描述】:

Dagger 中,我有时会看到有些组件只是扩展接口,而其他组件则使用dependencies

例如,我们有一个基础组件:

@Singleton
@Component(modules={...})
public interface BaseComponent {
    ...
}

版本 1:

@Singleton
@Component(modules={...})
public interface MyComponent extends BaseComponent {
    ...
}

第 2 版:

@CustomScope
@Component(modules={...}, dependencies= BaseComponent.class)
public interface MyComponent {
    ...
}

它们用于不同的场景吗?

【问题讨论】:

    标签: dagger-2


    【解决方案1】:

    如果您想创建组件的层次结构,执行此操作的标准方法是使用subcomponents 或使用dependent components

    您可以使用接口扩展来制作测试组件。这是比扩展模块更好的解决方案。官方文档的解释见here

    @Component(modules = {
      OAuthModule.class, // real auth
      FooServiceModule.class, // real backend
      OtherApplicationModule.class,
      /* … */ })
    interface ProductionComponent {
      Server server();
    }
    
    @Component(modules = {
      FakeAuthModule.class, // fake auth
      FakeFooServiceModule.class, // fake backend
      OtherApplicationModule.class,
      /* … */})
    interface TestComponent extends ProductionComponent {
      FakeAuthManager fakeAuthManager();
      FakeFooService fakeFooService();
    }
    

    【讨论】:

    • 我不会说 ComponentB 中的那些成员注入器一定是不可取的。这就是您在测试中使用 ComponentB 的方式。请参阅文档中的Option 2: Separate component configurationsgoogle.github.io/dagger/testing
    猜你喜欢
    • 2015-08-07
    • 2017-02-26
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多