简体   繁体   English

Dagger 与 Guice 中的运行时值注入

[英]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.我正在将一个项目从 Guice 迁移到 Dagger,并且我试图了解如何在运行时注入值。 Let's say I have a Guice module with the following configure method:假设我有一个带有以下配置方法的 Guice 模块:

  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.根据我的发现,我可以使用 AutoFactory,但我对 API 的理解不够好,而且我不知道在 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?这个示例将如何转换为 Dagger,以便我可以获得与 Guice 实现相同的功能? I really appreciate the help!我真的很感激帮助!

Dagger added its own assisted injection in version 2.31, so there isn't much to change. Dagger 在 2.31 版本中添加了自己的辅助注入,所以没有太大的改变。

The factory interface needs to be annotated with @AssistedFactory :工厂接口需要用@AssistedFactory注解:

@AssistedFactory
public interface InterfaceXFactory{

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

}

The constructor needs to be annotated with @AssistedInject :构造函数需要用@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. Dagger 会自行找到InterfaceXFactory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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