我可以在Dagger中使用某种辅助注射吗? [英] Can I use some kind of assisted Inject with Dagger?

查看:100
本文介绍了我可以在Dagger中使用某种辅助注射吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Google Guice或Gin可以指定不受依赖项注入框架控制的参数:

With Google Guice or Gin I can specify parameter with are not controlled by the dependency injection framework:

class SomeEditor {


  @Inject
  public SomeEditor(SomeClassA a, @Assisted("stage") SomeClassB b) {
  }

}

在创建SomeEditor的实例时指定了辅助参数stage.

The assisted parameter stage is specified at the time an instance of SomeEditor is created.

SomeClassA的实例是从对象图中获取的,而SomeClassB的实例是从运行时的调用者中获取的.

The instance of SomeClassA is taken from the object graph and the instance of SomeClassB is taken from the caller at runtime.

在Dagger中有类似的方法吗?

推荐答案

因为工厂是一种单独的样板,可以进行优化(

Because factories are a separate type of boilerplate to optimize away (see mailing list discussion here), Dagger leaves it to a sister project, AutoFactory. This provides the "assisted injection" functionality Guice offers via FactoryModuleBuilder, but with some extra benefits:

  • 您可以继续将AutoFactory与Guice或Dagger或任何其他JSR-330依赖项注入框架一起使用,因此即使您在它们之间进行切换,也可以继续使用AutoFactory.
  • 因为AutoFactory会生成代码,所以您无需编写一个表示构造函数的接口:AutoFactory将编写一个全新的类型供您进行编译. (如果愿意,或者从Guice迁移,也可以指定要实现的接口.)
  • 因为所有类型检查都在编译时发生,所以它会生成普通的旧Java,它不会因反射而变慢,并且可以与调试器和优化器一起很好地工作.这使得Auto库对于Android开发特别有用.

示例,从AutoFactory的README中提取,它将在@Inject注释的构造函数中生成SomeClassFactory,其中providedDepAcreate方法中使用depB:

Example, pulled from AutoFactory's README, which will produce a SomeClassFactory with providedDepA in an @Inject-annotated constructor and depB in a create method:

@AutoFactory
final class SomeClass {
  private final String providedDepA;
  private final String depB;

  SomeClass(@Provided @AQualifier String providedDepA, String depB) {
    this.providedDepA = providedDepA;
    this.depB = depB;
  }

  // …
}

这篇关于我可以在Dagger中使用某种辅助注射吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆