Dagger with Android:如何注入当前上下文?

Pau*_*aul 12 android dependency-injection dagger

回到我使用RoboGuice时,我能够将构造函数注入到我的类中,而RoboGuice会选择适当的上下文(注入一个Activity会有Activity上下文,注入Application会有当前的应用程序上下文,注入片段会有片段的活动的上下文等...).

Dagger是否有类似的方法来实现这一目标?

public class Thing {
    @Inject
    public class Thing(Context context){
       // if i'm injected in an Activity, I should be the current activity's context
       // if i'm injected in an Fragment, I should be the fragment's activity context
       // if i'm injected in a Service, I should be the service's context
       // etc...
    }
}
Run Code Online (Sandbox Code Playgroud)

Jak*_*ton 23

Dagger不了解Android.或者其他什么,真的.如果你想注射一些东西,你必须告诉Dagger.

您可以在示例中看到如何注入a Context 的示例.在这种情况下,限定符用于区分应用程序和活动1.

/**
 * Allow the application context to be injected but require that it be annotated with
 * {@link ForApplication @Annotation} to explicitly differentiate it from an activity context.
 */
@Provides @Singleton @ForApplication Context provideApplicationContext() {
  return application;
}
Run Code Online (Sandbox Code Playgroud)

编辑

不,您不能注入非限定类型,并且根据您执行注入的上下文更改该类型的实例.Dagger要求在编译时知道类型的源,并且因为对象图是不可变的,所以源不能被更改.

执行此操作的唯一方法是使用工厂,该工厂允许您指定用于创建对象的上下文.

public final class ThingFactory {
  private final Foo foo;
  private final Bar bar;

  @Inject public ThingFactory(Foo foo, Bar bar) {
    this.foo = foo;
    this.bar = bar;
  }

  public Thing get(Context context) {
    return new Thing(context, foo, bar);
  }
}
Run Code Online (Sandbox Code Playgroud)