1

I'm migrating a project from Guice to Dagger, and I'm trying to understand what to do with injection of values at runtime. Let's say I have a Guice module with the following configure method:

  void configure() {
    install(new FactoryModuleBuilder()
        .build(InterfaceXFactory.class));
  }

Factory interface,

public interface InterfaceXFactory{

  ClassX getClassX(
      @Assisted("a") String a,
      @Assisted("b") Integer b);

}

and finally:

  ClassX(
      final @Assisted("a") String a,
      final @Assisted("b") Integer b) {
    /.../
  }

What is the dagger equivalent of this configuration? Based on what I've found I could use AutoFactory, but I don't understand the API well enough and I'm lost on what this would look like in Dagger. Maybe that also isn't the best way to do this.

How would this example translate to Dagger, such that I can get the same functionality as the Guice implementation? I really appreciate the help!

babajaj
  • 168
  • 1
  • 2
  • 11

1 Answers1

1

Dagger added its own assisted injection in version 2.31, so there isn't much to change.

The factory interface needs to be annotated with @AssistedFactory:

@AssistedFactory
public interface InterfaceXFactory{

  ClassX getClassX(
      @Assisted("a") String a,
      @Assisted("b") Integer b);

}

The constructor needs to be annotated with @AssistedInject:

  @AssistedInject
  ClassX(
      final @Assisted("a") String a,
      final @Assisted("b") Integer b) {
    /*...*/
  }

Nothing needs to be added to the module; Dagger will find InterfaceXFactory on its own.

Nitrodon
  • 3,089
  • 1
  • 8
  • 15
  • So you're saying we can completely do away with the install(...).build in the module, or would it replaced by something else? Because we still have to pass the value into the component right? The dagger api shows something like this: serviceFactory.create(config); Does that seem right? – babajaj Jun 01 '21 at 19:03
  • 1
    `InterfaceXFactory` will automatically be available to any component or subcomponent that knows how to inject every non-assisted constructor parameter of `ClassX` (and has the same scope as `InterfaceXFactory` if applicable). In order to get a `ClassX` instance, you will need to pass a string `a` and integer `b` into an `InterfaceXFactory`; I imagine Guice works the same way. – Nitrodon Jun 01 '21 at 19:12