47

我正在 GitHub 上阅读Dagger2 Component Scopes Test的源代码,并且我看到了为名为 的活动定义的“自定义范围” @ActivityScope,但我在其他项目中看到了它,包括具有其范围的 4 模块CleanArchitecture 。@PerActivity

但从字面上看,@ActivityScope注释的代码如下:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.inject.Scope;

/**
 * Created by joesteele on 2/15/15.
 */
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {
}

它在模块中“神奇地”可用:

@Module
public class ActivityModule {
  @Provides @ActivityScope Picasso providePicasso(ComponentTest app, OkHttpClient client) {
    return new Picasso.Builder(app)
        .downloader(new OkHttpDownloader(client))
        .listener(new Picasso.Listener() {
          @Override public void onImageLoadFailed(Picasso picasso, Uri uri, Exception e) {
            Log.e("Picasso", "Failed to load image: " + uri.toString(), e);
          }
        })
        .build();
  }
}

CleanArchitecture示例:

@Scope
@Retention(RUNTIME)
public @interface PerActivity {}

@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
  //Exposed to sub-graphs.
  Activity activity();
}

@Module
public class ActivityModule {
  private final Activity activity;

  public ActivityModule(Activity activity) {
    this.activity = activity;
  }

  /**
  * Expose the activity to dependents in the graph.
  */
  @Provides @PerActivity Activity activity() {
    return this.activity;
  }
}

我可以清楚地看到这与 JSR-330 自定义范围有关,但我真的不明白这里到底发生了什么,以便此代码启用给定模块和/或给定模块提供的内容取决于实际的Activity生命周期,并且仅存在一个实例,但前提是该给定活动处于活动状态。

文档是这样说的:

Scope

Dagger 1 only supported a single scope: @Singleton. 
Dagger 2 allows users to any well-formed scope annotation. 
The Component docs describe the details of 
    how to properly apply scope to a component.

它说要查看组件文档页面,但这给了我 404。我也看到了这个,但是......

我可以请求一些帮助来澄清为什么指定这个自定义范围神奇地使Activity-level scopes工作没有问题吗?

(答案是,子作用域可以从其超作用域接收依赖关系,只要组件存在,子作用域就存在。并且您需要在模块上指定作用域,并且需要将组件依赖关系指定为子作用域一个超作用域。 )

4

2 回答 2

40

其实没有魔法。自定义范围注释只是注释。他们可以有任何名字。

作用域的第一个功能是告诉 Dagger 编译器在作用域组件中允许哪些作用域。这就是为什么@ActivityScope在非组件中使用依赖@ActivityScope会引发编译错误。

事实上,组件可以声明许多作用域(例如@ActivityScopeand @UiScope),而 Dagger 会将它们都视为单个作用域——这称为作用域别名。例如,它在多模块项目中很有用——当一个 Gradle 模块使用其 Dagger 模块定义一个范围,而另一个 Gradle 模块定义另一个范围时,它们都可以在定义 Dagger 组件的第三个 Gradle 模块中用作单个别名范围。

第二个功能是限制范围组件内允许的实例数量。支持多种类型的范围:

Unscoped - 当没有声明注释时。无作用域的依赖将在Provider没有任何缓存的情况下简单生成,并且在组件中创建的该依赖的任何实例对于每个新注入都是新的(如在构造函数中,或在模块提供方法中,或仅作为字段)。

自定义范围,例如@ActivityScope使用注释定义的@javax.inject.Scope注释 - 使用该范围声明的依赖项具有缓存Provider并生成双重检查锁,并且在具有相同范围声明的组件中只会为其创建单个实例,并且它的创建将是线程安全的。请注意,对于组件本身的每个实例,都将创建该依赖项的新实例。

可重用范围- 使用@dagger.Reusable注释声明 - 使用该范围声明的依赖项可以通过公共父组件在不同组件之间共享,并且将具有Provider生成单检查锁的缓存。当依赖项不一定需要具有单个实例但可以共享以提高单个组件或组件之间的性能(更少分配)时,它很有用。

有关范围如何工作的更多信息,请参阅用户指南和 Dagger 生成的代码。

如何定义实际范围是您的特权。定义范围组件的生命周期,何时创建和何时销毁 - 这是您的范围。例如@ActivityScope,与活动生命周期相关联并定义如下:

private ActivityComponent component;

@Override
protected void onCreate(Bundle savedInstanceState) {
    component = DaggerActivityComponent.builder().build();
    component.inject(this);
}

@Override
protected void onDestroy() {
    component = null;
    super.onDestroy();
}

所以没有魔法。通过使用它们的语义来定义你的范围。您可能还会发现此答案这些示例很有用。

编辑 14.10.2018扩展了范围函数和类型,以消除先前答案中的歧义。

于 2015-04-29T12:27:42.797 回答
19

值得注意的是,显然 Dagger2 在每个组件的模块中为每个作用域提供者创建了一个实例。

因此,为了在模块中获取范围提供程序,您需要为模块的提供程序方法指定范围。

@Module
public class YourModule {
    @Provides
    @YourScope //one per component
    public Something something() { return new SomethingImpl(); }

    @Provides //new instance per injection
    public Otherthing otherthing() { return new OtherthingImpl(); }
}

@Component
@YourScope
public interface YourComponent {
    Something something();
    Otherthing otherthing();

    void inject(YourThing yourThing); // only if you want field injection
}

编辑开始:虽然一般来说,你不需要在你的模块中实例化你自己的实现,所以你实际上可以这样做:

@Module
public abstract class YourModule {
    @Binds
    @YourScope //one per component
    public abstract Something something(SomethingImpl impl);

    @Binds //normally new instance per injection, depends on scope of Impl
    public abstract Otherthing otherthing(OtherthingImpl impl);
}

@Singleton
public class SomethingImpl implements Something {
    @Inject
    SomethingImpl() {
    }
}

// unscoped
public class OtherThingImpl implements OtherThing {
    @Inject
    OtherThingImpl() {
    }
}

@Component
@YourScope
public interface YourComponent {
    Something something();
    Otherthing otherthing();

    void inject(YourThing yourThing); // only if you want field injection
}

编辑结束

之后,参考基里尔的回答;本质上,“范围”本身仅确定它是与另一个范围不同的范围。使用组件依赖项(或子组件)创建一个子范围。

@Module
public class SubModule {
    @Provides
    @SubScope
    public ThatThing thatThing() { return new ThatThingImpl(); }
}

@Component(dependencies={YourComponent.class}, modules={SubModule.class})
@SubScope
public interface SubComponent extends YourComponent {
    ThatThing thatThing();

    void inject(SubThing subThing); // only if you want field injection
}

一个组件只能依赖于一个其他作用域组件。

于 2015-10-29T15:22:00.623 回答