Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger 2 extending interfaces vs dependent components

Tags:

dagger-2

In Dagger I sometimes see that there are components that just extend an interface while others use the dependencies.

So for example we have a base component:

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

Version 1:

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

And Version 2:

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

Are they used for different scenarios?

like image 596
Rgfvfk Iff Avatar asked Mar 31 '26 23:03

Rgfvfk Iff


1 Answers

If you want to create a hierarchy of components, the standard ways to do this are to use subcomponents or to use dependent components.

You can use interface extension to make test components. This is a better solution than extending modules. See here for an explanation from the official docs:

@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();
}
like image 92
4 revsDavid Rawson Avatar answered Apr 08 '26 05:04

4 revsDavid Rawson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!