简体   繁体   中英

Runtime value injection in Dagger vs. Guice

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM