不能在 Fragment 中使用 Toothpick.inject

Cannot use Toothpick.inject in Fragment

尝试在片段中使用 Toothpick DI 时出现奇怪的错误:

toothpick.registries.NoFactoryFoundException: No factory could be found for class android.app.Application. Check that the class has either a @Inject annotated constructor or contains @Inject annotated members. If using Registries, check that they are properly setup with annotation processor arguments.

我的片段:

public class ApplicationMenu extends SidebarFragment {

@Inject ApplicationsService applicationsService;
@Inject SectionsService sectionsService;

private EventBus bus = EventBus.getDefault();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Toothpick.inject(this, Toothpick.openScope(LauncherActivity.class)); // <- Erroring here       
}

...

}

Activity:

public class LauncherActivity extends SidebarActivity {

...

@Override
protected void onCreate(Bundle savedInstanceState) {

    Scope scope = Toothpick.openScopes(LauncherApplication.class, LauncherActivity.class);
    scope.bindScopeAnnotation(LauncherActivitySingleton.class);
    scope.installModules(new LauncherActivityModule(this));
    super.onCreate(savedInstanceState);
    Toothpick.inject(this, scope);

    setContentView(R.layout.activity_launcher);
    ButterKnife.bind(this);

    ...
}

...

}

奇怪的是我只在片段中得到错误,在其他地方(ViewRenderer、适配器、服务等)的所有注入都没有问题

我明白了。我错误地关闭了我的一项服务中的应用程序范围。该服务正在片段中使用,导致错误。

不幸的是,错误消息没有提供任何有用的信息,找到问题的唯一方法是分析和调试所有代码。

所以使用牙签 di 你必须非常小心范围生命周期。